我有两个nginx服务器通过docker在我的本地主机上运行。我希望一台服务器通过 ajax 调用另一台服务器 (api( 并做出反应。我一度让所有这些工作,但我再次启动我的服务器,我得到:
无法加载 http://localhost:8081/items?Title=butterflies:否 "访问控制允许源"标头存在于请求的上 资源。因此不允许使用原产地"http://localhost:8080" 访问。
所以Cors问题又回来了。我的 default.conf 中有以下代码:
server {
listen 8080;
root /app/public;
index index.php index.html;
charset utf-8;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
error_page 404 = /handle404.php;
location / {
try_files $uri $uri/ /index.php?$args;
add_header "Access-Control-Allow-Origin" "*" always;
add_header "Access-Control-Allow-Methods" "POST, GET, OPTIONS" always;
}
# Docker image version endpoints
location /version {
default_type text/plain;
rewrite ^/version/bisapi-php$ /version/bisapi-php.php last;
}
location ~ .php$ {
include fastcgi_params;
fastcgi_pass php:9000;
fastcgi_read_timeout 900;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
另外,这是我的代码,我在反应中调用 api:
var encodedURI = window.encodeURI('http://localhost:8081/items?Title=butterflies', { crossdomain: true });
return axios.get(encodedURI).then(function(response){
return response.data;
});
所以我显然在我的根中对我的网站有一个通用的调用。不知道为什么它不允许这样做。我对nginx有点陌生,所以请帮忙。
我将标头从位置\中取出并将它们放在服务器标签中以全局调用标头,并且它起作用了。我一定走上了一条不同的道路。