乐知付加密服务平台

如果你有资源, 平台可以帮你实现内容变现, 无需搭建知识付费服务平台。

点击访问官方网站 https://lezhifu.cc

扫码关注公众号 乐知付加密服务平台-微信公众号
解决服务跨域问题 | chenzuoli's blog

解决服务跨域问题

解决服务跨域问题,来看看我怎么解决的。

问题描述

报错代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const response = await fetch("http://43.153.96.195/chenzuoli/", {
// mode: 'no-cors',
//const response = await fetch("https://chatapi-chenzuoli.vercel.app/", {
//const response = await fetch("https://chatapi-new.vercel.app/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
"Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
message: messages,
currentModel,
}),
});

报错:

1
Access to fetch at 'http://43.153.96.195/chenzuoli/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

查找原因

根据提示,没仔细看,直接在fetch里面加了个mode: ‘no-cors’,就可以了,但是这样就不是跨域了,所以还是要解决跨域问题。
这个方案pass。

仔细看报错提示:access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
说明服务端没有设置Access-Control-Allow-Headers,所以要在服务端设置Access-Control-Allow-Headers。或者直接设置Access-Control-Allow-Origin为*。再或者客户端注释掉Access-Control-Allow-Headers。这三种方法都可以。

解决方案

修复代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const response = await fetch("http://43.153.96.195/chenzuoli/", {
// mode: 'no-cors',
//const response = await fetch("https://chatapi-chenzuoli.vercel.app/", {
//const response = await fetch("https://chatapi-new.vercel.app/", {
method: "POST",
headers: {
"Content-Type": "application/json",
// "Access-Control-Allow-Origin": "*",
// "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
// "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
// "Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
message: messages,
currentModel,
}),
});

总结

客户端和服务端都要设置Access-Control-Allow-Headers,不然就会报错。
要么都设置,要么都不设置,不然就会报错。


好了,我是zuoli,这就是我的全部分享,谢谢大家的观看,欢迎大家关注我的公众号:程序员写书,一起学习,一起进步。

-------------本文结束感谢您的阅读-------------