Enabling Cross Origin Resource sharing (CORS) in ExpressJS framework on NodeJS developed using Swagger

纵然是瞬间 提交于 2021-02-16 17:55:11

问题


I've hosted a nodejs server on localhost generated using Swagger and I'm trying to make API calls to it using Swagger UI again hosted on localhost. The network profile in chrome is showing connection refused everytime I'm making a call because CORS header are not added to the request.

This is my app.js file which was generated using Swagger:

'use strict';

var SwaggerExpress = require('swagger-express-mw');

var app = require('express')();
module.exports = app; // for testing

var config = {
  appRoot: __dirname // required config
};


SwaggerExpress.create(config, function(err, swaggerExpress) {
    if (err) { throw err; }

  // install middleware

  swaggerExpress.register(app);
  var port = process.env.PORT || 10010;
  app.listen(port);

  if (swaggerExpress.runner.swagger.paths['/hello']) {
    console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
  }
});

Till now I've tried the following methods and none of them has worked:

  1. Importing cors module from npm:

    npm install cors

In app.js

var cors = require('cors');

app.all(cors())
  1. Adding CORS using statements given in enable-cors website: http://enable-cors.org/server_expressjs.html

Both the above methods have failed for me, what can I try next? I can share more code samples if required.


回答1:


I guess you have not configure cors properly.

npm install cors

Usage

var cors = require('cors');

app.use(cors());

See more

CORS Support https://github.com/swagger-api/swagger-ui#cors-support



来源:https://stackoverflow.com/questions/39071430/enabling-cross-origin-resource-sharing-cors-in-expressjs-framework-on-nodejs-d

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