在Node.js中将JSON数据从前端写入后端 [英] Write JSON data from front-end to back-end in nodejs

查看:300
本文介绍了在Node.js中将JSON数据从前端写入后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ButtonClick.js和TakeData.js文件.我在TakeData.js中定义了我的json数据,如下所示:

I have ButtonClick.js and TakeData.js files. I defined my json data in TakeData.js as below

    var dataObj = {};
var locationsObj = "locations";
dataObj[locationsObj] = {};
dataObj[locationsObj].source = [];
dataObj[locationsObj].target = [];

当我单击ButtonClick.js中的按钮和以下代码段时

When I click the button in ButtonClick.js and the code snippet as below

button()
.container(g2)
.text(text2)
.count(1)
.cb(function()
{
    console.log(dataObj[locationsObj].source[0]);
    console.log(dataObj[locationsObj].source[1]);
    console.log(dataObj[locationsObj].target[0]);
    console.log(dataObj[locationsObj].target[1]);

    console.log("SaveFile");

})();

我想按以下方式将json数据发送到nodejs文件写入函数中.

I want to send json data into the nodejs file writing function as the following.

fs.writeFile('sample.txt', [need to insert my JSON], function(err) {
   if(err) return console.log(err);
    console.log('Hello JSON > sample.txt');
});

我该怎么做?还有另一种有效的方法吗?

How can I do that? Is there another effective way?

推荐答案

您的后端需要让HTTP服务器在前端可以访问的某些端口上侦听.然后,您的前端需要向后端发出AJAX请求(很可能是POST请求),然后在请求正文中发送所需的数据.

Your backend needs to have an HTTP server listening on some port that is accessible to your frontend. Then your frontend needs to make an AJAX request to your backend (most likely a POST request) and send the required data in the request body.

现在,您的后端需要处理请求,获取数据并将其写入文件,或使用该文件执行您想做的任何事情.

Now, your backend needs to handle the request, get the data and write it to the file or do whatever you want with that.

注意事项:

  • 如果使用Express,请使用body-parser
  • 记住有关CORS的信息

如果在后端使用Express,Hapi,Resify,LoopBack等更高级别的框架,而不是在Node中使用较低级别的http模块,则更容易.

It's easier if you use a higher level framework on the backend like Express, Hapi, Restify, LoopBack etc. instead of the low level http module in Node.

如果您在前端使用jQuery,Angular,React,Aurelia,Ember等框架,也会更容易

It's also easier if you use a framework on the frontend like jQuery, Angular, React, Aurelia, Ember etc.

这篇关于在Node.js中将JSON数据从前端写入后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆