【问题标题】:Passing a JSON object from clientside JavaScript to NodeJS将 JSON 对象从客户端 JavaScript 传递到 NodeJS
【发布时间】:2014-01-30 18:55:01
【问题描述】:

我有一个基于用户输入创建 JSON 对象的网页。然后我想以某种方式允许用户将此 JSON 对象提交给 NodeJS 脚本,以便处理/插入到 MySQL 数据库中。但是,我真的不确定如何做这样的事情——我能想到的最好的方法是某种形式的 POST,但我不确定从哪里开始。

因为我不知道这种方法会被描述为什么,所以我在网上查找任何教程或其他资源方面没有取得太大成功。

有人能推荐一些与此类相关的文章或文档吗?或者,至少,告诉我要搜索什么?谢谢。

编辑:这是我目前正在尝试使用的代码。我只是想在两边将 POST 数据类型从字符串转换为 JSON。

服务器端:

var express = require('express');
var fs = require('fs');
var app = express();

app.use(express.bodyParser());

app.get('/', function(req, res){
    console.log('GET /')
    //var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
    var html = fs.readFileSync('index.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

app.post('/', function(req, res){
    console.log('POST /');
    console.dir(req.body);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('thanks');
});

port = 8080;
app.listen(port);
console.log('Listening at http://localhost:' + port)

客户端:

<html>
<body>
    <form method="post" action="http://localhost:8080">
        Name: <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </form>

    <script type="text/JavaScript">
        console.log('begin');
        var http = new XMLHttpRequest();
        var params = "text=stuff";
        http.open("POST", "http://localhost:8080", true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //http.setRequestHeader("Content-length", params.length);
        //http.setRequestHeader("Connection", "close");

        http.onreadystatechange = function() {
            console.log('onreadystatechange');
            if (http.readyState == 4 && http.status == 200) {
                alert(http.responseText);
            }
            else {
                console.log('readyState=' + http.readyState + ', status: ' + http.status);
            }
        }

        console.log('sending...')
        http.send(params);
        console.log('end');

    </script>

</body>
</html>

【问题讨论】:

  • 一个帖子是正确的,如果你想这样做而不刷新页面,你需要AJAX。您还需要一条路由来在您的服务器上捕获它(在 Express 中,类似于 app.post("/api/test")

标签: javascript json node.js


【解决方案1】:

这是一个非常基本的示例,使用 jQuery 来执行 post 请求和一个 express 应用程序。我认为这应该是一个不错的起点。

// client side, passing data to the server
$.post("/foo/", { data : { foo : "bar" } }, function(temp) {
    // temp === "I am done";    
});

// serverside app.js

var express = require("express");

var app = express();

// will parse incoming JSON data and convert it into an object literal for you
app.use(express.json());
app.use(express.urlencoded());

app.post("/foo/", function(req, res) {
    // each key in req.body will match the keys in the data object that you passed in
    var myObject = req.body.data;
    // myObject.foo === "bar"
    res.send("I am done");
});

编辑: JSON.stringify() 和 JSON.parse() 将序列化/反序列化 JSON。 (jQuery 让这更容易,但如果你想使用纯 javascript)

更改为var params = "text=" + JSON.stringify({ foo : "bar" });

console.dir(JSON.parse(req.body.text));

它在我的本地对我有用。

【讨论】:

  • 感谢您的示例代码。不幸的是,我对 Express(以及一般的 Node.js)还是很陌生,所以我无法让它运行。你能指出我正确的方向吗?目前,我只是创建了一个按钮来触发 post 操作,如下所示: $.post("localhost:8080/hello", { data : { foo : "bar" } }, function(temp) { alert (温度);
  • 哪个部分不起作用,您可以使用您的快速应用程序的代码编辑您的问题。
  • 说实话,我不确定——我已经添加了上面的代码。感谢您的帮助!
  • 我已经设法让一个字符串 POST 工作......但是现在的问题是将其更改为 JSON。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多