How to prevent non-browser clients from sending requests to my server

后端 未结 2 1423
日久生厌
日久生厌 2021-01-03 10:58

I\'ve recently deployed my website and my back-end on the same vps, using nginx, but now when I do a request with PostMan to http://IP:port/route - I get the response from t

2条回答
  •  失恋的感觉
    2021-01-03 11:12

    Nodejs - Express CORS:

    npm i --save cors and then require or import according to your use case.

    To enable server-to-server and REST tools like Postman to access our API -

    var whitelist = ['http://example.com']
    var corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1 || !origin) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
      }
    }
    
    app.use(cors(corsOptions));
    

    To disable server-to-server and REST tools like Postman to access our API - Remove !origin from your if statement.

    var whitelist = ['http://example.com']
    var corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
      }
    }
    
    app.use(cors(corsOptions));
    

    It's really easy to implement and there are many options available with express cors module. Check full documentation here https://expressjs.com/en/resources/middleware/cors.html

提交回复
热议问题