用axios发出的请求不起作用,但是如果它与XMLHttpRequest

时间:2020-01-09 02:24:05

标签: reactjs axios

我正在与axios一起从request发出请求,该请求看起来像这样:

const data= axios.post(route, { username:'admin', password:'123' })
              .then(response =>{
                console.log(response)
              })
              .catch(err=>{console.log(err.response)

          })

但是它给我返回了状态400或401。我认为这与'CORS'有关,但是当我用react发出XMLHttpRequest请求时,它就成功了。这里是使用XMLHttpRequest发出的相同请求:

  var xhr = new XMLHttpRequest();
  var user = "admin";
  var password = "123";

  xhr.open('POST', route, true);
  xhr.addEventListener('load', function() {
    var responseObject = JSON.parse(this.response);
    console.log(responseObject);
    if (responseObject.token) {
          console.log(responseObject.token);
    } else {
          console.log('no');
    }
  });

  var sendObject = JSON.stringify({username: user, password: password});

  console.log('going to send', sendObject);

  xhr.send(sendObject);

如何正确使用axios发出请求?

日志:

log

2 个答案:

答案 0 :(得分:1)

Axios应该具有auth参数,如下所示:

auth: {
    username: 'janedoe',
    password: 's00pers3cret'
},

在此处查看文档:{​​{3}}

答案 1 :(得分:1)

如何在发布请求中设置内容类型参数?
你可以试试

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

let response = await axios.post(route, { username:'admin', password:'123' }, config);
console.log(response);