在线测试跨域的方法
🌙
手机阅读
本文目录结构
测试方案,在网页,打开控制台,如下代码
var token= "aaa";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://39.106.60.108:40619/api/market/token_status?token_account=0x000000000000000000000000000000000000000e');
xhr.setRequestHeader("x-access-token",token);
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
var token= "aaa";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stat.definer.cn/api/market/token_status?token_account=0x000000000000000000000000000000000000000e');
xhr.setRequestHeader("x-access-token",token);
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
如果是nginx转发的端口,需要配置!!!
如果代理地址已经允许跨域则不需要这些, 否则报错
如果代理地址已经允许跨域则不需要这些, 否则报错
# 直接请求nginx也是会报跨域错误的这里设置允许跨域
# 如果代理地址已经允许跨域则不需要这些, 否则报错(虽然这样nginx跨域就没意义了)
add_header Access-Control-Allow-Origin *;
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 = 'OPTIONS') {
return 204;
}
然后就是下面的配置
server {
listen 80;
server_name 192.168.16.190;
root /home/fastdfs/file/data;
index index.htm index.html;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header Cache-Control private;
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';
location / {
# 此处用于处理 H5 的 History时 重写的问题
if (!-e $request_filename) {
rewrite ^(.*) /index.html last;
break;
}
}
# 代理服务端接口
location /api {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
return 200;
}
proxy_pass http://192.168.16.191:3000/api; #将真正的请求代理到API 服务地址
}
location ^~/cross_origin/ {
rewrite ^/cross_origin/(.*)$ /$1 break;
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
return 200;
}
proxy_pass http://192.168.16.191:3000/cross_origin ; #将真正的请求代理到API 服务地址
}
}