axios跨域问题, 这种情况下 withCredentials 不能为true

前端报错信息如下:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/XXX' from origin 'http://127.0.0.1:8080' 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.

写了一个最简单的前端测试页面跨域访问后端,访问正常,确定后端是允许跨域的。

认真研读后,才明白:

当服务器端的Access-Control-Allow-Origin值设置为任意网站[*] 时,axios的 withCredentials 不能 = true 。

若需要跨域携带cookies,则以下3点都要做:1、服务器端的Access-Control-Allow-Origin值设置为指定网站(白名单),2、服务器端要设置Access-Control-Allow-Credentials   3、浏览器端的 withCredentials 必须 = true

当服务器端的Access-Control-Allow-Origin 没有设置时,无论浏览器端的 withCredentials 为true 还是 false 都不能跨域

之前查看资料,一直错误理解为:服务器端要设置Access-Control-Allow-Origin 且 浏览器端要 withCredentials=true 才能跨域。-->这个理解是错的!

### Axios 请求解决方案 在处理 Axios问题时,通常需要通过后端配置 CORS(Cross-Origin Resource Sharing)来解决问题。以下是针对不同后端框架的具体实现方式。 #### 1. 后端配置 CORS 解决问题 CORS 是一种浏览器安全机制,用于控制哪些外部名可以访问当前资源。如果服务端未正确设置 `Access-Control-Allow-Origin` 等头部字段,则会触发错误[^2]。 ##### Node.js 和 Express 配置 CORS 对于基于 Node.js 和 Express 的项目,可以通过安装并使用 `cors` 中间件来快速解决问题: ```javascript const express = require('express'); const cors = require('cors'); // 安装 npm i cors const app = express(); // 全局启用 CORS 支持 app.use(cors()); // 或者指定允许的源地址 app.use(cors({ origin: 'http://localhost:8889', credentials: true, })); app.post('/cert/certCompany/list2', (req, res) => { res.json({ message: 'Success!' }); }); app.listen(8888, () => { console.log('Server running on port 8888'); }); ``` 上述代码中,`origin` 参数指定了前端应用所在的 URL 地址,而 `credentials` 设置为 `true` 表示支持带 Cookie 的请求[^1]。 --- #### 2. Flask 配置 CORS 如果是 Python 基于 Flask 开发的服务端程序,可按照如下方式进行 CORS 配置: ```python from flask import Flask, request, make_response from flask_cors import CORS app = Flask(__name__) # 使用 Flask-CORS 插件全局开启 CORS 支持 CORS(app, supports_credentials=True) @app.route('/cert/certCompany/list2', methods=['POST']) def cert_company_list(): data = request.get_json() response_data = {'message': 'Success!'} return make_response(response_data) if __name__ == '__main__': app.run(port=8888) ``` 或者手动设置响应头的方式也可以达到相同效果[^4]: ```python @app.after_request def after_request(resp): resp = make_response(resp) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:8889' resp.headers['Access-Control-Allow-Methods'] = 'GET, POST' resp.headers['Access-Control-Allow-Headers'] = 'Content-Type' return resp ``` --- #### 3. 修改 Axios 请求参数 除了后端配置外,在某些情况下还可以调整 Axios 请求的行为以适应需求。例如,确保发送正确的 Content-Type 并携带必要的认证信息: ```javascript axios.post( 'http://localhost:8888/cert/certCompany/list2', JSON.stringify(this.searchParam), { headers: { 'Content-Type': 'application/json;charset=UTF-8', }, withCredentials: true, // 如果需要传递 Cookies } ).then((response) => { console.log(response.data); }).catch((error) => { console.error(error.message || error.toString()); }); ``` 注意:当启用了 `withCredentials` 属性时,服务端也需要显式声明支持凭证传输(即设置 `supports_credentials=true`),否则可能会引发预检失败等问题[^3]。 --- ### 总结 要彻底解决 Axios问题,建议优先从 **后端** 进行 CORS 配置,因为这是最根本的原因所在。无论是采用 Node.js/Express、Python/Flask 还是其他技术栈,都需要确保返回给客户端的 HTTP 响应包含了合法有效的 CORS 头部信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值