NodeJS - only OPTIONS request is send to the REST

2019-07-25 04:15发布

问题:

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