[英]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.