【问题标题】:CORS problems using generated [nodejs-server] code (SWAGGER)使用生成的 [nodejs-server] 代码 (SWAGGER) 的 CORS 问题
【发布时间】:2017-10-08 02:58:54
【问题描述】:

我根据我拥有的 swagger 规范生成了我的服务器代码 (nodejs-server)。

问题是,当我尝试从我的 UI(不同域)访问 API 时,我得到了一个众所周知的错误,即未启用 CORS:

XMLHttpRequest cannot load http://127.0.0.1:10010/events. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

我生成的index.js如下:

'use strict';

var fs = require('fs'),
    path = require('path'),
    http = require('http');

var app = require('connect')();
var swaggerTools = require('swagger-tools');
var jsyaml = require('js-yaml');
var serverPort = 10010;

// swaggerRouter configuration
var options = {
  swaggerUi: path.join(__dirname, '/swagger.json'),
  controllers: path.join(__dirname, './controllers'),
  useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode)
};

// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = fs.readFileSync(path.join(__dirname,'api/swagger.yaml'), 'utf8');
var swaggerDoc = jsyaml.safeLoad(spec);

// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {

  // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
  app.use(middleware.swaggerMetadata());

  // Validate Swagger requests
  app.use(middleware.swaggerValidator());

  // Route validated requests to appropriate controller
  app.use(middleware.swaggerRouter(options));

  // Serve the Swagger documents and Swagger UI
  app.use(middleware.swaggerUi());

  // Start the server
  http.createServer(app).listen(serverPort, function () {
    console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
    console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort);
  });

});

不确定如何使用此生成的代码启用 CORS。

【问题讨论】:

    标签: node.js cors swagger swagger-codegen


    【解决方案1】:

    在“初始化 Swagger 中间件”上方添加此代码,将域更改为正确的域。节点代码来自jvandemo's 对同一问题的回答No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

    // Add headers
    app.use(function (req, res, next) {
    
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://server.to.allow.access.from');
    
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    
    // Pass to next layer of middleware
    next();
    });
    

    swagger-codegen 不会覆盖现有的 index.js

    [main] INFO io.swagger.codegen.DefaultCodegen - 
    Skipped overwriting index.js as the file already exists in 
    C:\path\to\swagger-codegen\generated\nodejs\index.js
    

    【讨论】:

    • 谢谢,这解决了问题。顺便说一句,你使用招摇代码生成器吗?你认为是一个有用的工具吗?特别是nodejs-server 代码...如果您有任何有助于使用它的材料、资源、教程,请告诉我。我们将不胜感激。
    • 我使用 swagger-code gen 来模拟 API 响应,同时等待 Java 后端人员发挥作用。如果你使用 swagger 来定义 API,那么模拟背部的能力对我来说只是额外的。
    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多