1、post数据结构:
data: {
type: 'post',
name: 'post发送json参数'
}
2、js代码实现
var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/post', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onload = function () {
if (xhr.status === 200) {
var text = xhr.responseText;
if (success) success(JSON.parse(text));
} else {
if (error) error(xhr);
}
};

3、后端获取数据(Nodejs)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
app.post('/jsonPost', jsonParser, function(req, res) {
res.header('Access-Control-Allow-Origin', '*');
console.log('get application/json Params: ', req.body);
res.json({result: 'success', data: req.body});
});

本文介绍如何使用JavaScript发起POST请求并发送JSON格式的数据,同时展示了如何在Node.js后端接收并解析这些数据。
906

被折叠的 条评论
为什么被折叠?



