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