简体   繁体   English

NodeJS-仅将OPTIONS请求发送到REST API,不遵循POST或GET(Cloudflare)

[英]NodeJS - only OPTIONS request is send to the REST API, POST or GET doesn't follow (Cloudflare)

When my website calls the REST api (code below) then only the OPTIONS request goes through, the POST or GET request doesn't follow. 当我的网站调用REST api(下面的代码)时,只有OPTIONS请求通过,而POSTGET请求不会跟随。 The OPTIONS request successfully passes the CORS whitelist. OPTIONS请求成功通过了CORS白名单。 The POST or GET request isn't logged, it's also not blocked by the whitelist. POSTGET请求不会被记录,白名单也不会阻止它。 The weird thing is that the Google Recaptcha request works, all the third websites does, except for mine. 奇怪的是,除了我的以外,Google Recaptcha请求均有效,所有其他三个网站均有效。 The api is running on the same domain as the website, just another port. api在与网站相同的域上运行,只是另一个端口。

My website is using Cloudflare, Cloudflare constantly changes the IP addresses of the incomming requests. 我的网站正在使用Cloudflare,Cloudflare不断更改传入请求的IP地址。 My website his ip address is ipv6 after it went through the cloudflare proxy. 我的网站经过cloudflare代理后,其IP地址是ipv6。 The website his ip is listed as an ipv6 address in the whitelist array. 他的ip网站在白名单数组中列为ipv6地址。

const whitelist = ["*all the ip addresses"];

var corsOptions = {
    origin: (origin, callback) => {
        if (whitelist.indexOf(origin) !== -1) {
            callback(null, true)
        } else {
            callback('Not allowed by CORS');
        }
    }
};

const app = express();

mongoose.connect(*mongodb credentials*);

app.use((req, res, next) => {
    req.headers.origin = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    next();
});

app.use(morgan('combined'));
app.use(cors(corsOptions));
app.use(bodyParser.json({type: '*/*', limit: '2mb'}));
app.use(bodyParser.urlencoded({limit: '2mb', extended: true}));

app.use(*routing*);

module.exports = app;

app.use is only for registering middlewares. app.use仅用于注册中间件。 you need to specify a routing for each method you are using. 您需要为所使用的每种方法指定一个路由。 app.get, app.put, app.delete and etc. you can also use app.all for all methods You can find more information here : https://expressjs.com/en/guide/routing.html app.get,app.put,app.delete等。您还可以将app.all用于所有方法。您可以在此处找到更多信息: https ://expressjs.com/en/guide/routing.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM