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