Fetch 和 Axios 的区别

Difference between Fetch and Axios

有人可以向我解释为什么当我使用 fetch 并访问我的 nodejs api - 它是授权的但是当我尝试使用 axios 访问我的 api - 它是未经授权的。

这是我在 fetch 中使用的代码(来自教程:https://medium.com/@alexanderleon/implement-social-authentication-with-react-restful-api-9b44f4714fa)因为我正在研究他使用 passport-facebook-token 进行身份验证的方法。

(client -->(login fbsdk)--> fb --> (access token)--> client -->(pass access token)--> nodejs api --> (获取凭证) --> passport-fb-token --> (发送凭证) --> nodejs api --> (凭证)--> client)

const tokenBlob = new Blob([JSON.stringify({access_token: response.accessToken}, null, 2)], {type : 'application/json'});
    const options = {
        method: 'POST',
        body: tokenBlob,
        mode: 'cors',
        cache: 'default'
    };
    fetch('http://localhost:4000/api/v1/auth/facebook', options).then(r => {
        const token = r.headers.get('x-auth-token');
        r.json().then(user => {
            if (token) {
                this.setState({isAuthenticated: true, user, token})
            }
        });
    })

这是我的axios的代码

axios({
      method: 'post',
      url: 'http://localhost:4000/api/v1/auth/facebook',
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
      data: {
        access_token: response.access_token
      }
  })
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

这篇博客应该可以帮助您详细了解答案:

Fetch vs. Axios.js for making http requests

Axios is a Javascript library used to make http requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. Another feature that it has over .fetch() is that it performs automatic transforms of JSON data.

If you use .fetch() there is a two-step process when handing JSON data. The first is to make the actual request and then the second is to call the .json() method on the response.

The .fetch() method is a great step in the right direction of getting http requests native in ES6, but just know that if you use it there are a couple of gotchas that might be better handled by third-party libraries like Axios.

您应该将 axios 配置为在一个中央位置使用您的令牌。例如

export const configureAxios = (token) => {
    axios.interceptors.request.use(req => {
        // don't give our token to non-our servers
        if (isDomesticRequest(req.url)) {
            req.headers.Authorization = `Bearer ${token}`;
        }
        return req;
    });
}