繁体   English   中英

Elasticsearch CORS错误与ReactiveSearch

[英]Elasticsearch CORS error with ReactiveSearch

我已经使用我的Create React App进行了jwt身份验证的Node / Express服务器设置。 我正在使用CORS npm软件包和简单的中间件app.use(cors()); 解决预期的CORS相关问题及其正常工作。

现在,我想将Elasticsearch和ReactiveSearch添加到我的React应用程序中,并试图找出如何克服本地ES实例的CORS问题。

我的第一个猜测是,我需要创建一个单独的searchRoutes.js文件并实现ES本地运行并与我的React应用连接所需的任何CORS代码?

我一直在关注ReactiveSearch的文档(使用http-proxy-middleware),但没有获得任何成功...不断出现此CORS错误:无法加载http:// localhost:9200 / query-index / _msearch吗?:在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段的内容类型。

即使我相信我已经实施了CORS飞行前解决方案

app.options('/autocomplete', cors()); // this is for pre-flight

欢迎任何建议,链接或教程

更新:这是我的Nodejs index.js(服务器)

require('dotenv').config();
import express from 'express';
import http from 'http';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';
import proxy from 'http-proxy-middleware';
import cors from 'cors';
import compression from 'compression';

// import dotenv from 'dotenv'; // added
import router from './router';
// import { dbConfig } from './config';

// Express app init
const app = express();
// app.options('/query-index', cors()); // this is for pre-flight

/* This is where we specify options for the http-proxy-middleware
 * We set the target to appbase.io backend here. You can also
 * add your own backend url here */
const options = {
    // target: 'https://scalr.api.appbase.io/',
    target: 'http://localhost:9200',
    changeOrigin: true,
    // onProxyReq: (proxyReq, req) => {
    //     proxyReq.setHeader(
    //         'Authorization',
    //         `Basic ${btoa('cf7QByt5e:d2d60548-82a9-43cc-8b40-93cbbe75c34c')}`
    //     );
    //     /* transform the req body back from text */
    //     const { body } = req;
    //     if (body) {
    //         if (typeof body === 'object') {
    //             proxyReq.write(JSON.stringify(body));
    //         } else {
    //             proxyReq.write(body);
    //         }
    //     }
    // }
};

// Connect MongoDB
mongoose.connect(process.env.MONGODB_URI);
mongoose.set('debug', true);

// middleware
app.use(compression());
app.use(morgan('combined'));
app.use(cors()); // cors middleware
// https://stackoverflow.com/a/38345853/3125823
// Enable CORS from client-side from slatepeak
// app.use((req, res, next) => {
//   res.header('Access-Control-Allow-Origin', 'http://localhost:3333', 'http://localhost:9200'); // this can also be a list of urls
//   res.header('Access-Control-Allow-Methods', 'OPTIONS, PUT, GET, POST, DELETE');
//   res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-Auth-Token, Origin, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials');
//   // res.header('Access-Control-Allow-Credentials', 'true');
//   next();
// });
app.use(bodyParser.json({ type: '*/*' }));

/* This is how we can extend this logic to do extra stuff before
 * sending requests to our backend for example doing verification
 * of access tokens or performing some other task */
app.use('/query-index', (req, res, next) => {
    const { body } = req;
    console.log('Verifying requests ✔', body);
    /* After this we call next to tell express to proceed
     * to the next middleware function which happens to be our
     * proxy middleware */
    next();
});

/* Here we proxy all the requests from reactivesearch to our backend */
app.use('/query-index', proxy(options));

app.options('/query-index', cors()); // this is for pre-flight
app.get('/query-index', cors(), function(req, res, next) {
  res.json({ msg: 'This is CORS-enabled for route \/query-index'});
});

router(app);

const authPort = process.env.PORT || 3333; // default
const authServer = http.createServer(app);
authServer.listen(authPort);
console.log('Auth Server listening on:', authPort);

首先,您可以摆脱它,并为所有请求简单而简单地启用CORS:

app.use(cors())

让我们假设您仍然想要单条路线:您的代码指向一条路线“自动完成”,您发布的链接返回一个CORS错误,链接指向的是另一条路线“ query_index / ..”,因为您选择了一条路线。 -route启用方式,您需要解决此问题并在启用CORS的地方使用匹配的路由。

从您发布的内容来看,解决方案看起来还不完整。 如果您查看解决方案

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

并将其与您的路由进行比较,您应该在路由中添加一个回调,因为回调是逻辑发生的地方(传输到控制器等)。 可能看起来像这样:

app.get('/autocomplete', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for route \/autocomplete'})
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM