CORS error - I have set the headers but I keep getting the same error

135 Views Asked by At

I have an API in Node.js - TypeScript using cors:

import cors from 'cors';

const options: cors.CorsOptions = {
  origin: 'http://localhost:3000',
  methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
  allowedHeaders: [
    'Origin',
    'X-Requested-With',
    'Content-Type',
    'Accept',
    'X-Access-Token',
    'access-control-allow-origin',
  ],
  credentials: true,
  preflightContinue: false,
};

app.use(cors(options));
app.options('*', cors(options));

And a react app using axios:


import { useState } from 'react'
import axios from 'axios'
import './Login.css'

const Login = () => {
    const [ email, setEmail] = useState('');
    const [ password, setPassword] = useState('');

    const handleLogin = async () => {
        if(email !== '' && password !== ''){
            await axios.post('http://localhost:3003/allProducts', {Id: 1}).then((result) => {
                console.log(result)
            })
        }
    }

    return (
        <div className='login'>
            <h1>Login</h1>
            <form>
                <input type="email" placeholder='Email' onChange={(e) => setEmail(e.target.value)}/>
                <input type="password" placeholder='Password' onChange={(e) => setPassword(e.target.value)}/>
                <button type='button' onClick={handleLogin}>Login</button>
            </form>
            <p>Don't have an account yet?<span>Sign in.</span></p>
        </div>
    )
}

export default Login

Why am I receiving this CORS error if I have set the headers at the API and have tried A million of things at the Internet but I keep receiving the same error

enter image description here

1

There are 1 best solutions below

0
Mantvydas Zakarevičius On

Note: keep in mind that disabling CORS on production applications is not secure.

Try to update the CORS options because you may be omitting some of the allowed headers.

import cors from 'cors';

const options: cors.CorsOptions = {
  origin: 'http://localhost:3000',
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  preflightContinue: false,
  optionsSuccessStatus: 204,
};

app.use(cors(options));

In addition the whole cors usage in your Node.js application could be simplified by not passing options object (if you are currently only testing things out in development) and falling back to default settings which will enable content for all origins.

import cors from 'cors';

app.use(cors());