javascript - axios.create 和 CORS

标签 javascript ajax axios

我正在使用 axios 向端点发出带有数据的 POST 请求:

这有效:

import axios from 'axios';

axios.post('https://example.com/v1/login', {
  name: 'myuser',
  password: 'mypassword',
});

但这并不

import axios from 'axios';

export const apiBase = axios.create({
  baseURL: "https://example.com/v1/",
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

apiBase.post('login', {
  name: 'myuser',
  password: 'mypassword',
});

哪些日志:

Access to XMLHttpRequest at 'https://example.com/v1/login' 
from origin 'http://example.com' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: The 
value of the 'Access-Control-Allow-Origin' header in the response must 
not be the wildcard '*' when the request's credentials mode is 
'include'. The credentials mode of requests initiated by the 
XMLHttpRequest is controlled by the withCredentials attribute.

实际上,此请求中没有添加 header 'Content-Type'

有人知道这里出了什么问题吗?

<小时/>

编辑:修改以下评论

import axios from 'axios';

export const apiBase = axios.create({
  baseURL: "https://example.com/v1/",
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

apiBase.defaults.headers['Content-Type'] = 'pplication/json;charset=UTF-8';
apiBase.defaults.headers['Access-Control-Allow-Origin'] = 'http://example.com';
apiBase.defaults.headers['Host'] = 'example.com';
apiBase.defaults.headers['Referer'] = 'example.com';
apiBase.defaults.headers['Accept-Encoding'] = 'gzip, deflate, br';

apiBase.post('login', {
  name: 'myuser',
  password: 'mypassword',
});

仍然返回

Access to XMLHttpRequest at 'https://example.com/v1/login' 
from origin 'http://example.com' has been blocked by CORS policy: Response 
to preflight request doesn't pass access control check: The value of the 
'Access-Control-Allow-Origin' header in the response must not be the 
wildcard '*' when the request's credentials mode is 'include'. The 
credentials mode of requests initiated by the XMLHttpRequest is controlled 
by the withCredentials attribute.

最佳答案

设置凭据或将内容类型设置为 JSON 将触发 preflight request

预检响应的要求比非预检请求更严格。

其中之一是,正如错误消息所示,您不能使用通配符。您必须明确指定来源。你没有这样做。

And actually, no header 'Content-Type' is added to this request.

当然。预检未获得设置它的权限,因此从未发出请求。

关于javascript - axios.create 和 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61644995/

相关文章:

javascript - 在 React-Native 中检测和处理慢速互联网连接

javascript - 限制点击事件的范围

java - 我在哪里可以找到 Java/Python 中良好的 ajax 支持?

javascript - 设置3个元素的高度,取最大值,跨多行

javascript - 如何使用重复键动态生成 JSON 对象?

javascript - Angular 2 中 jQuery ajaxStart 的等效项

javascript - 如何使用 React 和 Axios 将 this.data 传递给其他组件

javascript - render 似乎在 componentDidMount 之前触发(使用 async/await)

javascript - Google Drive API 请求限制

javascript - 登录后无法获取和检索用户数据