如何通过 axios 调用具有基本身份验证的远程服务器?

How to call remote server with basic auth via axios?

我调用了受基本身份验证保护的远程服务器。

axios
  .get('http://localhost:9000/posts', {
    auth: {
      username: 'username'
      password: 'password'
    }}
  )
  .then(response => {
    console.log(response.data)
  })

这行不通。如果将 auth 设置为默认值 headers:

axios.defaults.auth = {username: 'username', password, 'password'}

或post

axios.post('http://localhost:9000/posts', {}, {
  headers: { 'Authorization': + 'Basic ' + btoa('username' + ':' + 'password') }
}).then(function(response) {
  console.log('Authenticated')
}).catch(function(error) {
  console.log('Error on Authentication')
})

两者都不行。

从它的Request Config来看,设置的方式是

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

放在哪里?


尝试过

axios({
  method: 'get',
  url: 'http://localhost:9000/posts',
  auth: {
     username: 'username',
     password: 'password'
  }
})
  .then(response => {
    console.log(response.data)
  })

也有错误No 'Access-Control-Allow-Origin' header is present on the requested resource.

axios({
 method: 'post',
 url: 'http://localhost:9000/posts', 
 auth: {
    username: 'username',
    password: 'password'
 }
})

应该可以! 查看 this 了解更多信息。

从问题中不确定:您在服务器身份验证上使用令牌还是 username/password?后者的答案在上面。如果你使用令牌,那么试试这个:

const requestOptions = {
    ...options,
    ...{
        headers: {
            authorization: token ? `Bearer ${token}` : ''
        }
    }
};

axios(url, requestOptions)
.then(res => {
    console.log('API call succeeded: ', res); // Read res.data
})
.catch(error => {
    if (error)
        setError(error.response);
    console.log('API call returned an error:', error);
});

至于 'Access-Control-Allow-Origin' - 这是 CORS 策略错误 (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) It means that you are making request from different domain than your server. This is not allowed by default in any browser (in order to avoid hacking...). You can't fix this on client. This is should be fixed on server by responding to API calls with additional set of HTTP Headers saying that your domain is allowed (read here https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin)。