简体   繁体   中英

React, axios, content-type

I have already searched a lot, but none of the solutions found work: Cannot send content-type by axios. but if I use the postman interceptor and I 'send' the request generated by axios this time it works: the node.js / express server correctly receives the request and body-parser works normally!

React side:

const API_URL = "http://localhost:8800/auth/";

const headers = {
  accept: 'application/json, text/plain, */*',
  'content-type': 'application/json;charset=UTF-8'
};

class AuthService {
  register(pseudo, email, password) {
    return axios.post(API_URL + "signup/",
      { pseudo, email, password },
      { headers: headers})
    .then(response => {
      if (response.data.accessToken) {
        localStorage.setItem("user", JSON.stringify(response.data));
      }
      return response.data;
    });
  }

server side

const app = express();
app.use(function (req, res, next) {
    console.log( req.headers);
    next();
}); 
app.use( bodyParser.urlencoded({ extended: true }), bodyParser.json()); 

Usually when I use axios I send the headers in a config variable like this and I stringify the body so it sends as JSON object and not a JS object.

const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };

    const body = JSON.stringify({arguments});
    try {
      const res = await axios.post(/url, body, config);

...

Here's a link to the docs for a little more reading about it:

https://github.com/axios/axios

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM