[英]CORS error on expressjs server with cors middleware already added
我有一个托管在 aws lightail 上的前端和 express js 服务器,它使用 ubuntu 和 nginx。
服务器设置为反向代理。 这是配置
location /api/ {
proxy_pass http://localhost:4000/api/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
我正在尝试从客户端发出发布请求(登录)以表达但我明白了
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
at http://localhost:4000/api/users/login. (Reason: CORS request did not succeed). Status
code: (null).
但我已经以多种方式在我的服务器上启用了 cors 但没有成功
const cors = require('cors');
const app = express();
const corsOption = {origin: "http://18.193.59.75:80"};
app.options("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers',
'Content-Type, Authorization, Content-Length, X-Requested-With');
res.send(200);});
//app.use(cors(corsOptions));
//app.options('*', cors(corsOptions));
添加下面给出的next()
处理程序,看看是否可以解决您的问题。
const cors = require('cors');
const app = express();
// const corsOption = {origin: "http://18.193.59.75:80"};
var corsOptions = function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers',
'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
}
app.use(corsOptions);
我在使用 cors 的移动设备上仍然遇到问题,我删除了所有配置并再次执行所有操作,只是为了意识到在我的前端我调用了'http://localhost:4000'
,我的服务器正在运行,但它正在运行服务器所以要访问它,我必须调用它http://18.193.59.75/api/endpoint
并且 nginx 将通过代理传递重定向到'http://localhost:4000'
。
这是我的 nginx 配置
server {
listen 80;
listen [::]:80;
server_name _;
location / {
root /var/www/website/client;
try_files $uri /index.html;
}
location /api {
proxy_pass http://localhost:4000;
}
还有我的 index.js 来自 express
const express = require('express');
const cors = require('cors');
const app = express();
// var corsOptions = function(req, res, next){
// res.header('Access-Control-Allow-Origin', '*');
// res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// res.header('Access-Control-Allow-Headers',
// 'Content-Type, Authorization, Content-Length, X-Requested-With');
// next();
// }
// app.use(corsOptions);
app.use(cors());
app.use(aux);
app.use(express.json());
app.use(express.urlencoded({extended: false}))
app.use('/api/appointments', require('./api/appointmnets'));
app.use('/api/users', require('./api/users'));
app.get('/test', (req, res) => {
res.json({'test' : 'successed'})
})
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`App listens to port ${PORT}`);
})
以及我从前端用来调用我的快速服务器的域
const domain = 'http://18.193.59.75:80/api/';
const domain = 'http://localhost:80/api'; //wronge
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.