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

最后都变了- 提交于 2019-12-11 07:43:19

问题


When my website calls the REST api (code below) then only the OPTIONS request goes through, the POST or GET request doesn't follow. The OPTIONS request successfully passes the CORS whitelist. The POST or GET request isn't logged, it's also not blocked by the whitelist. The weird thing is that the Google Recaptcha request works, all the third websites does, except for mine. The api is running on the same domain as the website, just another port.

My website is using Cloudflare, Cloudflare constantly changes the IP addresses of the incomming requests. My website his ip address is ipv6 after it went through the cloudflare proxy. The website his ip is listed as an ipv6 address in the whitelist array.

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;

回答1:


app.use is only for registering middlewares. 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



来源:https://stackoverflow.com/questions/52034699/nodejs-only-options-request-is-send-to-the-rest-api-post-or-get-doesnt-follo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!