为了更熟悉 node.js,我创建了一个带有 Node 服务器的新网站,我正在向服务器发布数据,但我不知道如何读取请求中的 JSON 数据:
客户请求:
function addSymptom(name) {
$.ajax({
type: 'POST',
url: '/addSymptom',
data: {
symName: name
},
success: function (data) {
listSymptoms();
},
contentType: "application/json",
dataType: 'json'
});
}
服务器处理程序:
app.post('/addSymptom', function (req, res) {
var newSymptom = req.body;
console.log(newSymptom); // undefined :(
res.send(JSON.stringify({
result: 'success'
}));
});
为什么 request.body 未定义?我应该以其他方式读取请求正文中的“symName”字段吗?
最佳答案
一定要在 node.js 上添加 bodyParser 模块..
如果您使用的是 Express 3.x/4.x,您只需确保包含 bodyParser:
Express 3.x
app.use(express.bodyParser({limit : '50mb'}));
Express 4.x
在你的包文件中:
"body-parser": "~1.0.0",
或者运行 npm-install body-parser
然后在您的 node.js 服务器中:
var bodyParser = require('body-parser');
// create our app
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());
示例链接: http://code.runnable.com/U0sU598vXio2uD-1/example-reading-form-input-with-express-4-0-and-body-parser-for-node-js 3.没有 express
如果出于某种原因您决定不使用 express,您可能需要绑定(bind)到套接字的数据处理程序以读取数据。
这是一篇关于此事的文章: http://blog.frankgrimm.net/2010/11/howto-access-http-message-body-post-data-in-node-js/
关于javascript - 从 Node 中的请求中提取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30977395/