I am receiving a couple of errors trying to send a fetch request from the client side to a Node.js API. Upon pressing the submit button, I receive the following errors in the console log:
[Error] Origin http://127.0.0.1:4000 is not allowed by Access-Control-Allow-Origin.
[Error] Fetch API cannot load http://localhost:4300/contact/ due to access control checks.
[Error] Failed to load resource: Origin http://127.0.0.1:4000 is not allowed by Access-Control-Allow-Origin. (contact, line 0)
I have the following in my server.js file in my API:
app.use((req, res, next) => {
console.log(new Date(), req.method, req.originalUrl);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
So I'm not sure as to why that isn't working. Additionally, in the Node.js console I receive this error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at parse (/Users/marcofusco/Desktop/Cloud Innovations/APIs/Cloud Innovations API/node_modules/body-parser/lib/types/json.js:89:19)
at /Users/marcofusco/Desktop/Cloud Innovations/APIs/Cloud Innovations API/node_modules/body-parser/lib/read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:198:9)
at invokeCallback (/Users/marcofusco/Desktop/Cloud Innovations/APIs/Cloud Innovations API/node_modules/raw-body/index.js:231:16)
at done (/Users/marcofusco/Desktop/Cloud Innovations/APIs/Cloud Innovations API/node_modules/raw-body/index.js:220:7)
at IncomingMessage.onEnd (/Users/marcofusco/Desktop/Cloud Innovations/APIs/Cloud Innovations API/node_modules/raw-body/index.js:280:7)
at IncomingMessage.emit (node:events:388:22)
at endReadableNT (node:internal/streams/readable:1305:12)
at processTicksAndRejections (node:internal/process/task_queues:80:21)
I'm sending a packet of data from the client side to my Node.js API as so:
async function createRequestTask(req, method, headers, body) {
return new Promise(async (resolve) => {
const apiUrl = baseURL;
var reqData = {
method: method,
headers: headers,
mode: "cors",
cache: "no-cache",
credentials: 'same-origin',
};
reqData.headers["Content-Type"] = "application/json";
if (body !== undefined) reqData.body = body;
var apiReq = new Request(`${apiUrl}/${req}/`, reqData);
var res = await fetch(apiReq)
.then(response => { return response.json(); })
.catch((error) => { return { auth: error } })
return resolve(res.response);
});
}
Why am I seeing these errors? Thanks.