[英]body data not sent in axios request
我正在嘗試通過 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以注銷參數
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
就像@MaieonBrix 所說的那樣,確保您的標頭包含您要發送的內容類型。
看起來你只剩下兩點才能讓它工作:
一:http 方法應該設置為POST
而不是GET
因為你想發送一些東西。
二:然后您可以添加 http 標頭(就像您對授權標頭所做的那樣) 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 })
如果您收到“bodyParser 已棄用”的錯誤消息,請嘗試以下操作 -
app.use(express.json()); //To parse JSON bodies (Applicable for Express 4.16+)
如果您想從 HTTP 請求的正文中獲取數據,請使用“post”方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.