【发布时间】:2022-01-20 23:42:07
【问题描述】:
我想解决 react native 和 iphone 的问题。我在 Gcloud 上有 API,比如说 ip 34.xx.xx.xx,还有一个域名 myapp.com。在域名 myapp.com 上,我有 SSL 证书和 https,在 ip 地址上,我有带有 https 的 nginx 服务器,但没有证书。我该怎么做才能使 axios 获取对我的域名的请求,而不会出现 CORS 错误等。
我解决 CORS 问题的一种方法是 nginx 设置:
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
使用此设置 CORS 错误消失,API 停止发送数据,在 Postman 中我收到此错误: Postman error screenshot
这是获取请求:
axios.post(`${Ip}login`,
{
email: email,
password: password
},
{headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(function (response) {
const stringToken = String(response.data.access_token)
setToken(stringToken)
sighIn(stringToken)
setLoading(false)
})
.catch(function (error) {
console.log("login section")
【问题讨论】:
-
请嵌入你得到的错误以便能够帮助你
标签: react-native axios fetch-api fastapi