开放所有跨域 ----前端和后端

### 2025-8-5 开放所有跨域 ----后端
```
//开放所有跨域
response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("Access-Control-Allow-Credentials", "true");
response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
response.AddHeader("Access-Control-Allow-Headers", "Accept,Origin,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization");

//开放所有跨域---add 其他属性2023-10-18
//response.AppendHeader("Access-Control-Allow-Origin", "*");
//response.AppendHeader("Access-Control-ALLow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
//response.AppendHeader("Access-Control-ALLow-Headers", "*");
//response.AppendHeader("Access-Control-Allow-Credentials", "true");
//response.AppendHeader("Access-Control-Allow-Private-Network", "true");
//response.AppendHeader("Access-Control-Max-Age", "3600");


response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("Access-Control-ALLow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
response.AddHeader("Access-Control-ALLow-Headers", "*");
response.AddHeader("Access-Control-Allow-Credentials", "true");
response.AddHeader("Access-Control-Allow-Private-Network", "true");
response.AddHeader("Access-Control-Max-Age", "3600");
```
### 2025-8-5 开放所有跨域 ----前端
```
跨源请求(cors)失败解决办法
jquery的ajax跨源请求(cors)失败解决办法
js中ajax请求前添加 jQuery.support.cors = true;
或者js中ajax请求中header处理
headers中的
'Content-Type': 'application/json' 给去掉了
"Access-Control-Allow-Origin", "*" 添加

JQuery -跨域处理
浏览器支持:并非所有浏览器都完全支持 CORS。例如,IE8 和 IE9 仅部分支持 CORS,需要在调用处指定
jQuery.support.cors = true

VUE前端应用和后端 API 服务器 -跨域处理
VUE,Vite,Webpack都可以配置的,都有个server,在其中配置proxy代理就可以了
devServer.proxy#Type: string | Object如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:
module.exports = {
  devServer: {
    proxy: 'http://localhost:4000'
  }
}
这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000。如果你想要更多的代理控制行为,也可以使用一个 path: options 成对的对象。完整的选项可以查阅 http-proxy-middleware 。
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: '<url>',
        ws: true,
        changeOrigin: true,
        pathRewrite:{
                   "^/api":""
         }
      },
      '/foo': {
        target: '<other_url>'
      }
    }
  }
}

注意:例如上述配置中的<url >是http://127.0.0.1:27100, '/api':是 '/Terminal': 的话,按照你这配置的话,那原来代码中的请求路径就为 Terminal?t=IsDeviceOnLine,会自动拼接成http://127.0.0.1:27100/Terminal?t=IsDeviceOnLine地址,那么这个pathRewrite 这个属性要注视掉。
例如上述配置中的<url >是http://127.0.0.1:27100/Terminal, '/api':是 '/Terminal': 的话,按照你这配置的话,那原来代码中的请求路径就为 Terminal?t=IsDeviceOnLine,会自动拼接成http://127.0.0.1:27100/Terminal/Terminal?t=IsDeviceOnLine地址,同时pathRewrite 这个属性要保留,保留的话就会把/Terminal制成“”,最终地址就会变成http://127.0.0.1:27100/Terminal?t=IsDeviceOnLine


跨域 fetch
fetch("http://127.0.0.1:27100/Terminal?t=IsDeviceOnLine", {
"headers": {
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\"Google Chrome\";v=\"141\", \"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"141\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site"
},
"body": "{\"CommandName\":\"IsDeviceOnLine\"}",
"method": "POST",
"mode": "cors",
"credentials": "omit"
}).then(res => {
console.log("res === ", res);
});

js
fetch("https://example.com", { credentials: "include",});
备注: 当请求使用 credentials: 'include' 时,响应的 Access-Control-Allow-Origin 不能使用通配符 "*"。在这种情况下,Access-Control-Allow-Origin 必须是当前请求的源,在使用 CORS Unblock 插件的情况下请求仍会失败。
备注: 无论怎么设置,浏览器都不应在 预检请求 中发送凭据。了解更多:跨域资源共享 > 附带身份凭证的请求

Fetch API 使用示例

Fetch API 是一种现代化的网络请求工具,支持异步操作并基于 Promise,使代码更简洁易读。以下是一个使用 fetch 发送 POST 请求的示例:
fetch(api_base_url + '/api/scan', {
method: 'POST', // 指定请求方法
credentials: 'include', // 包括 cookies 在请求中
headers: {
'Content-Type': 'application/json' // 设置请求头
},
body: JSON.stringify({ key: 'value' }) // 请求体,发送 JSON 数据
})
then(response => {
if (!response.ok) {
throw new Error('网络响应失败: ' + response.statusText);
}
return response.json(); // 解析 JSON 响应
})
then(data => console.log('成功:', data))
catch(error => console.error('错误:', error));
注意事项
credentials: 'include':用于在跨域请求中发送 cookies,但需要服务器正确配置 CORS。
错误处理:fetch 不会因 HTTP 状态码(如 404 或 500)自动抛出错误,需要手动检查 response.ok。
JSON 数据:通过 JSON.stringify() 将对象转换为字符串,并设置 Content-Type 为 application/json。
替代方案
对于简单的 GET 请求,可以直接使用默认配置:
fetch(api_base_url + '/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('错误:', error));
Fetch API 提供了灵活性和强大的功能,是现代 Web 开发中不可或缺的工具。

客户现场的请求--实际使用
const service = (option) => fetch("http://127.0.0.1:27100" + option.url, {
"headers": {
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\"Google Chrome\";v=\"141\", \"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"141\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site"
},
"body": JSON.stringify(option.data),
"method": option.method,
"mode": "cors",
"credentials": "omit"
}).then(response => {
if(!response.ok) {
throw new Error('请检查设备服务是否正常开启');
}
return response.json();
}).catch(error => {
console.error(error);
});

export default service

window浏览器控制台操作 案例
window.fetch("http://127.0.0.1:27100/Terminal?t=IsDeviceOnLine", {
"headers": {
"accept": "/",
"accept-language": "zh-CN,zh;q=0.9",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": ""Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": ""Windows"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site"
},
"body": "{"CommandName":"IsDeviceOnLine"}",
"method": "POST",
"mode": "cors",
"credentials": "omit"
}) .then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('错误:', error));


XMLHttpRequest API 使用示例
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

// 创建 XMLHttpRequest 对象
//var xhr = new XMLHttpRequest();

// 配置请求
xhr.open('GET', 'https://api.example.com/data', true);

// 设置请求头(如果需要的话)
// xhr.setRequestHeader('Content-Type', 'application/json');

// 定义回调函数
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
// 请求成功,处理响应
console.log('Response:', xhr.responseText);
} else {
// 处理错误
console.error('Error:', xhr.statusText);
}
};

// 处理网络错误
xhr.onerror = function () {
console.error('Request failed');
};

// 发送请求
xhr.send();

 

JQuery -跨域处理
浏览器支持:并非所有浏览器都完全支持 CORS。例如,IE8 和 IE9 仅部分支持 CORS,需要在调用处指定
jQuery.support.cors = true

 

fetch 请求遇到cors问题

fetch("https://www.baidu.com/home/weather/getweather?citycode=1078&bsToken=3c699e2c5cfeb3699d48f1cf3c56dfb2&indextype=manht&_req_seqid=0xa4191b6302e263e2&asyn=1&t=1760861499929&sid=63141_64005_64983_65247_65179_65415_65424_65456_65453_65361_65538_65593_65618_65636_65664_65668_65681_65687_65757_65729_65759_65786_65790_65866", {
"headers": {
"accept": "text/plain, */*; q=0.01",
"accept-language": "zh-CN,zh;q=0.9",
"ps-dataurlconfigqid": "0xa4191b6302e263e2",
"sec-ch-ua": "\"Google Chrome\";v=\"141\", \"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"141\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://www.baidu.com/",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
});


当你在网页中遇到“fetch 请求时拒绝连接,因为它违反了文档的内容安全策略”(CORS, 即跨源资源共享策略)的错误时,通常是因为浏览器出于安全考虑,阻止了跨域请求。为了解决这个问题,你可以采取以下几种方法:

1. 服务器端设置CORS
在你的服务器上设置CORS头部是最直接的方法。这可以通过在服务器响应中添加适当的HTTP头部来实现。例如,如果你使用的是Node.js和Express,你可以在Express应用中添加以下中间件来允许所有域的访问:

javascript
Copy Code
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors()); // 允许所有域的访问

// 或者指定允许的域
app.use(cors({
origin: 'https://example.com' // 替换为你的目标域名
}));

app.listen(3000, () => {
console.log('Server is running on port 3000');
});
2. 使用代理服务器
如果你无法控制服务器设置CORS,或者出于其他原因需要在客户端解决这个问题,你可以使用代理服务器。这意味着你的前端应用将请求发送到你的服务器,然后你的服务器再将请求转发到目标服务器。这样,你的服务器可以设置CORS头部,从而避免直接违反浏览器的安全策略。

例如,使用Node.js创建一个简单的代理服务器:

javascript
Copy Code
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();

app.use(cors()); // 允许所有域的访问

app.get('/api/proxy', async (req, res) => {
try {
const response = await axios.get('https://example.com/api/data', { // 目标URL
headers: {
// 可以添加任何必要的头,例如认证信息等
}
});
res.json(response.data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});

app.listen(4000, () => {
console.log('Proxy server is running on port 4000');
});
3. JSONP(仅限于GET请求)
如果你的需求只是简单的数据获取(比如只做GET请求),可以考虑使用JSONP(JSON with Padding),尽管这不是一个安全的解决方案,但它可以作为临时解决方案。JSONP通过在URL中添加一个回调函数来实现跨域请求。这种方法在现代Web开发中已经较少使用,因为CORS提供了更安全、更灵活的解决方案。

4. 检查Content-Security-Policy头部
有时候,问题可能不是由CORS引起的,而是由内容安全策略(Content-Security-Policy, CSP)头部配置不当引起的。确保你的CSP头部没有阻止特定的资源加载。例如,如果你的应用需要从外部加载脚本或样式表,确保CSP头部允许这些操作。

http
Copy Code
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' https://trusted-cdn.com; img-src 'self';
确保调整CSP头部以适应你的实际需求。以上就是解决跨域请求被浏览器阻止的一些方法。选择最适合你当前情况

```

posted @ 2026-01-07 15:16  至尊龙骑  阅读(13)  评论(0)    收藏  举报