【发布时间】:2018-08-06 09:36:20
【问题描述】:
我使用 Axios 作为我的 HTTP 客户端来调用第 3 方 API。 Express for my server 和 cors 包通过更改 HTTP 标头来解决 CORS 问题。但是错误Failed to load https://api.abalin.net/namedays?day=25&month=11: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.总是出现。
尽管使用了server.options("*", cors());,但我尝试通过使用 cors 包添加配置选项以及此website 推荐的基本配置来手动配置标头。最后,我确实将原点设置为http://http://localhost:3000/。
服务器.js
const express = require("express");
const next = require("next");
const cors = require("cors");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
server.options("*", cors());
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(3000, err => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});
Abalin.js
class Abalin extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
Axios.get("https://api.abalin.net/namedays?day=25&month=11").then(res => {
console.log(res);
});
}
render() {
return (
<div>
<p>Hello World</p>
</div>
);
}
}
export default Abalin;
感谢您调查此问题。我感谢您的时间和精力。
【问题讨论】:
标签: reactjs express cors axios next.js