javascript - 获取 API 未发布到 Node.js 服务器(正文为空)
问题描述
我正在尝试使用 fetch() 发布到我正在运行的另一个 Node.js 服务器。当我取出标题时,我的控制台会打印“{}”。当我保留它们时,调用该函数时不会打印任何内容。
我尝试过使用 curl,我也收到了“{}”。
//Server.js (what I am trying to POST to)
var express = require('express');
var app = express();
var PORT = 4000;
app.use(express.json());
app.post('/', function (req, res) {
console.log(req.body);
})
app.listen(PORT, function () {
console.log('server running on port: ' + PORT);
})
//Post function (this is inside a separate React component which will perform the POST)
postContents() {
var data = { username: 'example' };
fetch('http://localhost:4000/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', JSON.stringify(response)));
}
解决方案
您必须使用 body-parser 作为快速服务器的中间件。
const express = require('express');
const app = express();
const PORT = 4000;
const bodyParser = require('body-parser');
app.use(bodyParser.json());
推荐阅读
- c++ - 将矢量排序到中大(前端和小尾)的最佳方法
- javascript - 选中/取消选中包装在 vue 3 中的父 div 中的复选框
- flask - 使用flask socketio将私人消息发送到特定的会话ID
- c++ - 二进制搜索没有给出正确的输出
- python-3.x - Websockets 在订阅多个共享时出现问题,它覆盖了以前的内容
- javascript - 如何在反应中将道具从路由数组传递给组件
- android - Android-Seekbar 奇怪地跳来跳去
- java - Micronaut 只使用一个数据库,甚至连接两个数据库
- c++ - 如何使用 avrdude 从 cpp 文件生成 hex 文件
- networking - 查找 Windows 机器的外部 IP