猿问

Axios.create 和 CORS

我正在使用 axios 向端点发出包含数据的帖子请求:


这有效:


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.

实际上,没有向此请求添加标头。'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.


炎炎设计
浏览 239回答 2
2回答

慕码人2483693

设置凭据或将内容类型设置为 JSON 将触发预检请求。对预检的响应的要求比对非预检请求的要求更严格。其中之一是,正如错误消息所说,您不能使用通配符。您必须显式指定原点。你没有那样做。实际上,没有向此请求添加标头“内容类型”。自然。印前检查未获得设置它的权限,因此从未发出请求。

喵喵时光机

无论出于何种原因,Axios 都不允许在将 withCredentials 设置为 true 时以 JSON 对象的形式在 POST 请求中发送数据。在传递数据之前,您需要将数据字符串化。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答