1
您好,我正在开发一个反应/快速应用程序。我已经能够从我的服务器发出GET请求,但是,我无法发出POST请求。当我这样做时,我的服务器正在返回一个空的主体。我将body-parser作为一个依赖项,接受json作为内容,但仍然没有运行空的正文。我的代码和服务器/客户端依赖关系如下。如果你们看到我没有看到的东西,请告诉我。从React快速发送POST请求返回空体
Index.js
const express = require('express');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
//routes
require('./routes/sendMessageToEmail')(app);
require('./routes/helloWorld')(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 1111;
app.listen(port);
后当我切换围绕在我的路线在我的index.js文件中声明的顺序,例如,宣布路由线
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
行,我得到一个未定义的反对空的身体。
POST路线
module.exports = app => {
app.post('/api/message', (req, res) => {
console.log('>>>>>>>>>> ', req.body);
res.send(req.body)
});
}
我的console.log将返回一个空的对象。我已经在postman中发布了post请求,从我的浏览器,curl等等。我得到了一个200状态响应,但是,body仍然是空的。
服务器的package.json
{
"name": "Blog",
"version": "1.0.0",
"engines": {
"node": "6.11.1"
},
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "npm run start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.2",
"concurrently": "^3.5.0",
"express": "^4.15.3"
}
}
客户的package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.16.2",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-iframe": "^1.0.7",
"react-redux": "^5.0.5",
"react-router-dom": "^4.1.2",
"react-scroll": "^1.5.4",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"semantic-ui-react": "^0.71.3"
},
"devDependencies": {
"react-scripts": "1.0.10"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:1111/"
}
阵营POST路线
import axios from 'axios';
const sendToExpress = (input) => {
return fetch('/api/message', {
mode: 'no-cors',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({message: 'asdfafa;k'})
//body: JSON.stringify({"message": input})
})
}
//ACTION CREATORS
export const sendInputToServer = (input) => ({
type: 'SEND_INPUT_TO_SERVER', payload: sendToExpress(input)
});
任何帮助表示赞赏这里弄清楚为什么我的帖子reques t正在返回一个空的身体。
你的路由肯定需要去体解析器中间件。另外,在你的路线中,你可能也想使用res.json()而不是result.send,因为你的客户希望接收json – SlimSim
嘿,我切换了路线并尝试了res.json(),但仍然没有雪茄。还有什么你可以看到我的代码可能是一个问题,后体返回空? – Generaldeep