繁体   English   中英

将JSON对象从客户端JavaScript传递到NodeJS

[英]Passing a JSON object from clientside JavaScript to NodeJS

我有一个网页,可根据用户输入创建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>

这是一个非常基本的示例,使用jQuery进行发布请求和快速应用。 我认为这应该是一个体面的起点。

// 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));

它为我在本地工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM