body data not sent in axios request

后端 未结 3 1397
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 23:14

I am trying to send data through axios request to my backend script, but the body looks empty.

Here\'s a request sent from front-end:

axios.request({         


        
相关标签:
3条回答
  • 2020-12-16 00:00

    GET requests should not have a body.

    Change the method from 'GET' to 'POST'

    Like so:

    axios.request({
      method: 'POST',
      url: `http://localhost:4444/next/api`,
      headers: {
        'Authorization': token
      },
      data: {
        next_swastik: 'lets add something here'
      },
    
    })
    

    and change your api to expect a post

    app.post('/next/api', verifyToken, function(req, res) {
    console.log(req.body);
    });
    

    or

    Change the data property to params

    axios.request({
      method: 'GET',
      url: `http://localhost:4444/next/api`,
      headers: {
        'Authorization': token
      },
      params: {
        next_swastik: 'lets add something here'
      },
    
    })
    

    and change the api to log out the params

    app.get('/next/api', verifyToken, function(req, res) {
    console.log(req.params);
    });
    

    and like @MaieonBrix said, make sure that your headers contain the content type that you are sending.

    0 讨论(0)
  • 2020-12-16 00:00

    Try this

    this.axios('realties', { params: this.filter })
    
    0 讨论(0)
  • 2020-12-16 00:15

    It looks like you only have two points left to make it work :

    • one : the http method should be set to POST instead of GET since you want to send something.

    • two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`

    On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.

    I suppose your server is using express, here is how you will do it with 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 讨论(0)
提交回复
热议问题