我的计算机上运行着 nginx,它为solid.js 前端和两个express.js 服务器提供服务。 我正在尝试获取在我的 Express 应用程序之一中公开的端点。 一切正常,直到我在 nginx 配置中为我的可靠应用程序指定 server_name 。 我收到 net::ERR_BLOCKED_BY_CLIENT 的错误
前端应用程序的 nginx 配置
server {
listen 80;
server_name home.localhost;
location / {
root D:/Programming/JavaScript/mocks/nginx-tests/solid-statis/dist;
try_files $uri /index.html =404;
}
}
我的后端应用程序的 nginx 配置
server {
listen 80;
server_name api.localhost;
location /first-api/ {
proxy_pass http://localhost:7777/;
}
location /second-api/ {
proxy_pass http://ocalhost:7778/;
}
}
我尝试将所有这些添加到我的 nginx 后端配置中
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
我也尝试过
add_header Access-Control-Allow-Origin *;
根据提供的信息,问题似乎可能与 Nginx 中后端应用程序的配置有关。具体来说,该问题与 CORS(跨源资源共享)政策有关,该政策可能会由于来源不同而阻碍前端应用程序访问后端 API。
要解决此问题,您应该将必要的 CORS 标头合并到后端服务器配置中。由于您使用 Express.js 作为后端,因此您可以使用
cors
中间件来管理 CORS 标头。
具体操作方法如下:
cors
包:npm install cors
cors
中间件为后端 API 启用 CORS:const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
// ... Define your API routes and other middleware ...
// Initiate your server
const port = 7777; // Replace with your desired port number
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
对在端口 7778 上运行的其他后端应用程序重复上述步骤。
通过在 Express.js 应用程序中启用 CORS,您将允许 Solid.js 提供的前端应用程序访问后端 API,而不会遇到
net::ERR_BLOCKED_BY_CLIENT
错误。
此外,您可以从 Nginx 后端配置中删除
add_header Access-Control-Allow-Origin *;
和其他与代理相关的配置,因为 CORS 处理应使用 cors
中间件在 Express.js 应用程序中完成。这样,您就可以保持 Nginx 配置简单,并专注于为前端提供服务并将请求路由到后端应用程序。