-2

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.

mfusco
  • 23
  • 1
  • 5
  • Don't write your own custom CORS middleware. Please just use the industry standard [cors middleware](https://github.com/expressjs/cors) – Phil Aug 18 '22 at 00:05
  • @Phil Thank you, that solves one problem. I'm still getting that syntax error in my Node.js API – mfusco Aug 18 '22 at 00:11
  • What _client_ (browser) are you using? The error messages for these sorts of problems are usually more detailed. – Phil Aug 18 '22 at 00:11
  • @Phil I'm on Safari – mfusco Aug 18 '22 at 00:12
  • My guess is that there are two problems here... 1) You're registering `express.json()` or `bodyParser.json()` _before_ the cors middleware. `app.use(cors())` should be first. 2) You aren't sending valid JSON from your client-side code – Phil Aug 18 '22 at 00:13
  • @Phil Yes, I have app.use(express.json()) before any of my endpoints. Does that mean I have to convert the reqData object into JSON on my client side before sending the fetch request? – mfusco Aug 18 '22 at 00:17

1 Answers1

-3

This is a CORS error. It's a security measure because your frontend and backend are on different origins (domains or ports).

You need to add a header in your request headers that says this: Access-Control-Allow-Origin: *

This will fix the issue.

Wor Chan
  • 139
  • 1
  • 11