CORS -从react应用程序到oas 3-基于nodejs工具的自定义头的Post请求Rest API返回网络错误

vc9ivgsu  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(121)

我对React和Nodejs都是新手,对CORS的概念也很陌生。我遇到的问题是,当我从React应用程序向Nodejs Rest API发送带有“version”头的POST请求时。它没有正确响应pre-flight请求,以允许在请求中使用“version”头,所以我得到了一个'NetworkError'响应我的请求。我已经遇到了一个问题,将中间件添加到由oas 3-tools生成的应用程序中,所以有一个功能可以正确插入它,而不需要'版本'header一切似乎都在按预期工作.似乎express路由器实际上正在处理这里的请求:

// for options requests, respond with a default if nothing else responds
  if (req.method === 'OPTIONS') {
    done = wrap(done, function(old, err) {
      if (err || options.length === 0) return old(err);
      sendOptionsResponse(res, options, old);
    });
  }

并且Cors代码似乎没有被命中
React请求:

const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Origin', 'http://' + globals.restApiUrl);
      headers.append('version', '1');

      const response = await fetch(
        'http://' + globals.restApiUrl + '/User?Username=username&Password=password',
        {
          mode: 'cors',
          method: 'POST',
          headers: headers,
        }
      );

      if (response.ok) {
        navigate('/homepage');
      } else {
        const json = await response.json();
        throw json;
      }
    } catch (error) {
      console.log('Error:', error);
    }
  };

配置Nodejs(初始尝试):

'use strict'; 
var insertMiddleware = require('./helpers/insertMiddleware.js');
var path = require('path');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 8080;
const cors = require('cors');

/* swaggerRouter configuration*/
var options = {
    routing: {
        controllers: path.join(__dirname, './controllers'),
    },

};

// Genarate the app
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, 'api/openapi.yaml'), options);
var app = expressAppConfig.getApp();

// Add cors middleware 
insertMiddleware.insertMiddleware(app, cors({origin: '*', allowedHeaders: '*'}));

// Initialize the Swagger middleware
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);
});

第二次尝试:

'use strict';
var path = require('path');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 8080;
const cors = require('cors');

/* swaggerRouter configuration*/
var options = {
    routing: {
        controllers: path.join(__dirname, './controllers'),
        preMiddleware: [cors({ origin: '*', allowedHeaders: '*' })],
        postMiddleware: [cors({ origin: '*', allowedHeaders: '*' })],
    },

};

// Genarate the app
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, 'api/openapi.yaml'), options);
var app = expressAppConfig.getApp();

// Initialize the Swagger middleware
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);
});
ffvjumwh

ffvjumwh1#

所以问题是cor在路由器堆栈中的位置,insertMiddleware函数从堆栈顶部插入任何新的中间件3个索引,但cor需要在oas 3-tools生成的应用程序上插入17个索引:)

module.exports.insertMiddleware = function insertMiddleware(app, middleware, positionFromTheTopOfTheStack) {

    var newPositionFromTheTopOfTheStack = 2;
    if (positionFromTheTopOfTheStack !== undefined)
    {
        newPositionFromTheTopOfTheStack = positionFromTheTopOfTheStack;
    }
    // Get the length of the stack before we add the new middleware 
    const stacksOriginalLength = app._router.stack.length;
    // Add the new middleware to the top of the stack
    app.use(middleware);
    // Take what was the last X elements in the stack and move them back to the end of the array
    app._router.stack.push(...app._router.stack.splice(stacksOriginalLength - newPositionFromTheTopOfTheStack, newPositionFromTheTopOfTheStack));
}

像这样调用这个函数:

insertMiddleware.insertMiddleware(app, cors({ origin: '*', allowedHeaders: '*' }), 16);

成功了

相关问题