gpt4 book ai didi

node.js - CORS 问题,HapiJS HAPI-16

转载 作者:搜寻专家 更新时间:2023-11-01 00:04:21 25 4
gpt4 key购买 nike

编辑:这只适用于 HapiJS 16- 版本

我有一个使用 React 的客户端和一个使用 HapiJS 的服务器。

在客户端中,我尝试向服务器发出 POST 请求,但出现以下错误

OPTIONS http://localhost:3001/sentilize/ 404 (Not Found) localhost/:1 Failed to load http://localhost:3001/sentilize/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.

我在端口 3001 上运行服务器。我在 3000 上运行客户端。

如有任何帮助/指导,我们将不胜感激。此外,我可以使用 POSTMAN 成功地向服务器发出发布请求。它只是来自 React,它不起作用。

这是我的 server.js

import Hapi from "hapi";
import { routes } from "./routes";

const server = Hapi.server({
host: "localhost",
port: 3001,
routes: { cors: true }
});

// Register Routes
routes.forEach(route => {
server.route(route);
});

// We need to install babel-polyfill
// because async and await are in es7
async function start() {
try {
await server.start();
} catch (err) {
console.log(err);
}
console.log("Hapii server is running");
}

start();

这是在前端进行调用的代码

  fetchSentiment = () => {
axios
.post("/", {
sentence: this.state.value
})
.then(response => {
this.setState({ sentiment: response.data });
})
.catch(error => {
console.log("Error: ", error);
});
};

我有一个 axios 实例设置如下 (axios-sentiment.js)

import axios from "axios";

const instance = axios.create({
baseURL: "http://localhost:3001/sentilize"
});

export default instance;

最佳答案

服务器配置看起来正确。有可能正在使用的客户端 HTTP 库没有发送正确的 header 。特别是,确保请求具有 Origin header 。请注意,cors: true 设置仅支持某些 CORS 场景,并非在所有情况下都有效。了解 simplified requests了解 CORS 的一些细微差别。然后 route.options.cors文档将更有意义,如果需要,您可以将其设置为调整其行为的对象。

一些其他不相关的提示:

  • async await 在 Node 7.6 及更高版本中受支持。您可能根本不需要 babel 或 babel-polyfill。参见 node.green了解支持哪些语言功能。
  • 尝试/捕获 Promise 链只是为了记录错误是一种不应再使用的旧模式。 Promise 错误曾经被默认吞没,但现在不再存在了,它们被现代版本的 Node(以及浏览器)记录下来。如果你想更激进,你可以使用 throw-rejects还可以故意使进程崩溃,而不仅仅是记录日志,这样更容易发现错误。

关于node.js - CORS 问题,HapiJS HAPI-16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49331473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com