javascript - 从客户端 JS 发送 JSON,服务器 Nodejs 读取为 [object object]
问题描述
您好,我只是想通过 POST 更新欢迎消息,据我所知,我正在从客户端 JavaScript 发送 JSON,在 NodeJS 端它显示为 [object object] I'我试过 req.body 并返回“未定义”。我想知道如何从我发送到 nodejs 服务器的 JSON 中提取我的欢迎消息并保存到 .JSON 以便以后能够从客户端中提取。
我已经尝试过jsonstringify(req)
,这会在我的 nodejs cmd 中返回一个大错误,如果有必要,我可以粘贴它。
nodejs 服务器 POST,它会写入文件 welcome.json,它会写入[object object]
or undefined
,这取决于我是否使用req.body
or req
。
app.post('/update', function (req, res) {
fs.writeFile(__dirname + '/rqsts/welcome.json', req.body, function () {
console.log('We got a Post request' + req.body);
});
});
这是我的客户端http post请求:
function submit() {
var text_Input = document.getElementById('textinput').value;
var testing = document.getElementById('testme');
var welcome_array = {
welcome: ""
};
welcome_array.welcome = text_Input;
var welcomeJSON = JSON.stringify(welcome_array);
var url = 'http://localhost:8080/update';
var http = new XMLHttpRequest();
http.open('POST', url, false); // false for synchronous request
Add_Para(welcomeJSON, testing);
http.send(welcomeJSON);
}
Add_Para 是我为进行故障排除而制作的一个功能,它使用请求的数据“welcomeJSON”在所述 html 中添加了一个段落
解决方案
如果您使用的是 expres 4.16 或更高版本,请使用
app.use(express.json());
没有必要使用bodyParser
推荐阅读
- python - 如何模拟更真实的物体运动?
- sql - HQL 的子查询不返回任何内容
- android - 带有 Firebase 托管的 Android Instant App
- javascript - 作为反应,如何选择/检查单选按钮?
- google-cloud-platform - 为什么我的 MX 记录没有在 Google Cloud Platform 上刷新?
- reactjs - React Redux,组件内部状态同步
- node.js - 在会话存储中使用多个数据库
- python - 从名称列表中创建大量字典
- javascript - 使用 Select Option 更改 DOM 并检查没有必填字段
- azure-pipelines-release-pipeline - 在 TFS 2017 本地部署中创建版本时提示输入变量