[Fixed] Issue with Cors in React.js localhost and Node Express server

Issue

I’ve been trying to call my API hosted on Digital Ocean droplet as a Node.js Express server. Problem I’m running into is CORS. Here are my client side calls and errors.

export const postRequest = async (route, data, headers) => {
    let config = {
        headers: headers
    }
    let dataString = JSON.stringify(data)
    return instance.post(route, dataString, config)
    .then((response) => {
        return response.data
    })
    .catch((err) => {
        console.log(err);
        return {error: err}
    });
}
export const login = (email, password) => {
    const data = {
        email:email,
        password:password
    };
    
    const headers = {
        'Content-Type': 'application/json'
    }

    return postRequest('/login', data, headers);
}

Server side is just a simple express server with no cores implemented into the code. I tried using app.use(cors()) but no luck, so I’m starting fresh right now. Frontend is react js and axios.

Error I’m getting is

Access to XMLHttpRequest at 'https://example.com/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What do I need to do here? Both on client and server side.

Solution

NEVERMIND!!! I made an error on client side. To fix this error, go to your server code,

npm install --save cors

add

const cors = require('cors');

app.use(cors());

restart your server and you should be good to go.

Leave a Reply

(*) Required, Your email will not be published