后端工程師寫完接口之后傳到遠程服務器上,為了便于本地調試,我特地去服務器上的nginx配置允許CORS。
配置過程
服務必須返回 Access-Control-Allow-Origin : enabledhost.com 的 http response,才會允許跨域訪問,我先去服務器上找到 nginx 的配置文件,然后直接配置以下內容:
location /
{
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
include fastcgi.conf;
}
完事之后進行接口調用,發現還是不管用,于是就進行各種搜,網上的答案五花八門,有說GET類型和POST類型的請求配置不一樣,也有說一樣的。 最后還是問了搞后端的朋友,應該寫在一個關于php支持的配置文件里才行,于是我更正了配置:
location —— [^/]/.php(/|$)
{
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
include fastcgi.conf;
}
至此,就OK了,大家在進行nginx跨域配置時需要注意以下幾點:
1、Access-Control-Allow-Origin 不要像我一樣設置 * ,這樣不安全。我只是為了臨時使用方便,后面還會關掉此設置
2、設置時寫在php相關的location配置中
3、不要忘記這條配置 add_header Access-Control-Allow-Headers X-Requested-With; 網上搜到的答案大部分都少這一條。