我已经有了一个用于jwt身份验证的Node / Express服务器设置,可以使用我的Create React App。我使用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不允许使用content-type。
即使我相信我已经实施了CORS预检solution
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);
答案 0 :(得分:0)
首先,你可以摆脱它,简单明了地为所有请求启用CORS:
app.use(cors())
假设你仍然想要单行:你的代码是指一条路线“自动完成”,你发布的链接返回一个CORS错误,指的是另一条路径“query_index / ..”,因为你选择了要使用单路径启用方式,您需要修复此问题并使用启用CORS的匹配路由。
根据您发布的内容,您的解决方案看起来更加不完整。 如果你看solution:
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'})
})
答案 1 :(得分:0)
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 配置文件中