身体数据未在axios请求中发送

问题描述 投票:2回答:3

我试图通过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);

})

但我得到{}空身。我正在获取标题和其他数据,但不是数据。

javascript node.js reactjs axios
3个回答
5
投票

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说,确保您的标题包含您要发送的内容类型。


3
投票

看起来你只剩下两点让它工作:

  • 一: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 */

0
投票

试试这个

this.axios('realties', { params: this.filter })
© www.soinside.com 2019 - 2024. All rights reserved.