如何解決Access-Control-Allow-Origin跨域問題
前提環(huán)境:在A服務(wù)器,調(diào)用B服務(wù)器的資源,報(bào)錯(cuò)出現(xiàn)找不到請(qǐng)求頭Access-Control-Allow-Origin,輸入跨域問題, 需要使用配置nginx來處理
例如:A服務(wù)器是liunx系統(tǒng)部署了一個(gè)java程序,B服務(wù)器是本地服務(wù)器,A服務(wù)器需要請(qǐng)求訪問B服務(wù)器的資源,可以用nginx代理來請(qǐng)求到B服務(wù)器的資源。
配置nginx.conf文件
提示:先下載啟動(dòng)nginx,官網(wǎng)下載
鏈接: nginx
步驟:下載完成后安裝運(yùn)行在A服務(wù)器上面,先運(yùn)行看看有沒有問題,這里不細(xì)說,然后找到開始配置nginx.conf文件(重點(diǎn))
代碼如下(示例):
server {
listen 9800;
server_name localhost;
#后臺(tái)接口配置
location ~ /quartz/ {
proxy_pass http://192.168.X.XXX:9830;
proxy_read_timeout 360s;
proxy_send_timeout 360s;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Front-End-Https on;
add_header 'Access-Control-Allow-Methods' 'GET,POST';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
}
}
location / {
root html;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
一、如何配置你的nginx.conf
添加一個(gè)server{},這是你的服務(wù),listen參數(shù)是你要監(jiān)聽的端口,這個(gè)端口可以自定義,server_name localhost,這個(gè)一般就是A服務(wù)器的域名地址,記住這個(gè)地址+端口+/參數(shù)/(127.0.0.1:9800/quartz/) 是映射location,也就是請(qǐng)求的地址會(huì)被代理成 proxy_pass http://192.168.X.XXX:9830這個(gè)地址,A服務(wù)器就可以跨服務(wù)器請(qǐng)求B服務(wù)器的資源;
二、添加Access-Control-Allow-Methods請(qǐng)求頭
代碼如下(示例):
add_header Front-End-Https on;
add_header 'Access-Control-Allow-Methods' 'GET,POST';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
header頭字段 | 含義 | 取值 |
---|---|---|
Access-Control-Allow-Credentials | 響應(yīng)頭表示是否可以將對(duì)請(qǐng)求的響應(yīng)暴露給頁面 | true/false |
Access-Control-Allow-Headers | 表示此次請(qǐng)求中可以使用那些header字段 | 符合請(qǐng)求頭規(guī)范的字符串 |
Access-Control-Allow-Methods | 表示此次請(qǐng)求中可以使用那些請(qǐng)求方法 | GET/POST(多個(gè)使用逗號(hào)隔開) |
Access-Control-Allow-Origin | 一種跨域策略,標(biāo)識(shí)的Response header,用來解決資源的跨域權(quán)限問題。 | 標(biāo)識(shí)符 |
總結(jié)
提示:這里對(duì)文章進(jìn)行總結(jié):
文章來源:http://www.zghlxwxcb.cn/news/detail-460090.html
以上就是今天要講的內(nèi)容,本文僅僅簡(jiǎn)單介紹了用nginx來解決Access-Control-Allow-Origin跨域問題;文章來源地址http://www.zghlxwxcb.cn/news/detail-460090.html
到了這里,關(guān)于Access-Control-Allow-Origin跨域問題,使用Nginx配置來解決的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!