Axios发布请求引发错误请求

时间:2020-03-24 15:07:25

标签: reactjs symfony

登录成功后,我正在尝试获取jwt令牌。它有效,当我使用curl时,它会返回令牌,像这样:

curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username": "admin@admin.com", "password": "000000"}'

我得到结果:

{"token":"eyJ0eXAi..."}

但是从前端应用程序中我得到了错误:

{"error":{"code":400,"message":"Bad Request","exception":[{"message":"The key \"username\" must be provided."...

前端的代码如下:

let session_url = 'http://localhost/api/login_check';
let username =  'admin@admin.com'
let password = '000000';
axios.post(session_url, {
    withCredentials: true,
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    },{
        auth: {
            username: username,
            password: password
        }}).then(function(response) {
        console.log('Authenticated');
    }).catch(function(error) {
        console.log('Error on Authentication');
    });

我尝试了所有来自google的答案,但是我找不到我做错了什么。

1 个答案:

答案 0 :(得分:0)

尝试像这样的axios:

let session_url = 'http://localhost/api/login_check';
let username =  'admin@admin.com'
let password = '000000';

axios(session_url, {
  method: "post",
  withCredentials: true,
  data: {
    username,
    password
  },
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  }
}).then(function(response) {
  console.log('Authenticated');
}).catch(function(error) {
  console.log('Error on Authentication');
});

希望对您有帮助!