当前位置: 首页 > 知识库问答 >
问题:

Elasticsearch CORS错误与ReactiveSearch

曹臻
2023-03-14

我已经为jwt身份验证设置了一个节点/Express服务器,可以与我的Create React应用程序一起使用。我用的是CORS npm包和简单中间件< code > app . use(CORS());来解决预期的CORS相关问题及其正常工作。

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

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

我一直在遵循ReactiveSearch的文档(使用http-proxy-middleware ),但没有任何成功...一直得到这个CORS错误:加载http://localhost:9200/query-index/_ m search失败?:预检响应中的Access-Control-Allow-Headers不允许请求标头字段内容类型。

尽管我相信我已经实现了CORS飞行前解决方案

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

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

更新:这是我的Nodejs索引.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);

共有2个答案

韩恺
2023-03-14
http.cors.enabled: true
http.cors.allow-credentials: true
http.cors.allow-origin: '*'
http.cors.allow-headers: X-Requested-With, X-Auth-Token, Content-Type, Content-Length, Authorization, Access-Control-Allow-Headers, Accept 

您需要将这些 cors 权限添加到您的 elasticsearch.yml 配置文件

锺离旻
2023-03-14

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

app.use(cors())

让我们假设您仍然想使用单一路由:您的代码引用了一条路由“autocomplete”,即您发布的返回CORS错误的链接,它引用的是另一条路径“query_index/..”,因为您选择使用单一路由启用方式,所以您需要修复此问题并使用启用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'})
})
 类似资料:
  • 问题内容: 我使用这个proguard文件: 但是在对代码进行一些更新之后,我出现了以下错误: 我尝试了: 但是仍然不起作用,怎么了?我真的不明白该怎么办。PS,您对优化我的文件有什么建议吗?提前致谢。 问题答案: 我有同样的问题。 我在这里找到了答案,并且对我有用:如何将ApacheHTTPAPI(旧版)添加为build.grade的编译时依赖项? 在顶层build.gradle文件中添加: 在

  • 问题内容: 在PHP中使用的符号,以测试或从不同的或。 例如return ,return 。因此,如果所讨论的子字符串的位置在开始时就在以0为基数的字符串中进行搜索,您将获得哪个PHP可以与之区分开。 有没有办法在Python中做到这一点? 问题答案: 在Python中, 的身份操作测试(,)。 测试逻辑相等性(因此)的运算符。 从技术上讲,这两者都不完全等同于PHP ,后者比较了逻辑相等性和Py

  • 但还是不行,怎么了?我真的不明白我能做什么。PS为了优化我的文件,你有什么建议吗?提前道谢。

  • 简介 当你开始一个新的 Lumen 项目时,Lumen 已经帮你配置好错误和异常处理的操作。另外,Lumen 也集成了 Monolog 日志函数库,Monolog 支持和提供多种强大的日志处理功能。 有关日志的更多内容,请阅读 Laravel 的完整 日志文档.

  • 请帮助我在Spring启动应用程序,它不工作。我太紧张了。 文件夹列表 null 导入org.springframework.boot.springapplication;导入org.springframework.boot.autocigure.springbootapplication MainController类: 包装控制器; 和错误消息: 并且在资源/模板中有一个index.htm文件

  • 我试图使用Keycloak API(通过keycloak-admin库在node中),但系统地得到错误403。 我通过库成功地获得了一个访问令牌;通过调用(在master realm上)。 当我查看我的令牌内部时,我似乎有能够查询用户的正确角色: