我试图通过axios请求将数据发送到我的后端脚本,但是身体看起来是空的。
这是从前端发送的请求:
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
}).then((res)=>{
console.log("api call sucessfull",res);
}).catch((err)=>{
console.log("api call unsucessfull",err);
this.props.toggleLoading(false);
})
这是一个后端:
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.body);
})
但我得到{}
空身。我正在获取标题和其他数据,但不是数据。
GET请求不应该有一个正文。
将方法从“GET”更改为“POST”
像这样:
axios.request({
method: 'POST',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
})
并改变你的api以期待一个帖子
app.post('/next/api', verifyToken, function(req, res) {
console.log(req.body);
});
要么
将data
属性更改为params
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
params: {
next_swastik: 'lets add something here'
},
})
并更改api以注销params
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
和@MaieonBrix说,确保您的标题包含您要发送的内容类型。
看起来你只剩下两点让它工作:
POST
而不是GET
,因为你想发送一些东西。Content-Type
:'application / json`在后端不要忘记使用某种身体解析器实用程序包像这样:body-parser并使用您的应用程序进行设置。
我想你的服务器正在使用express,以下是如何用express表达的:
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */
试试这个
this.axios('realties', { params: this.filter })