I am using Axios as my HTTP client to call a 3rd party APIs. Express for my server and the cors package to fix the CORS issue by changing the HTTP headers. But the error 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.
always appears.
Despite using server.options("*", cors());
, I tried manually configured the header by adding the configuration options using the cors package as well as the basic configuration recommended by this website. Lastly, I did set the origin to http://http://localhost:3000/.
Server.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;
Thanks for looking into this question. I appreciate your time and effort.