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
Note: keep in mind that disabling
CORSonproductionapplications is not secure.Try to update the CORS
optionsbecause you may be omitting some of the allowed headers.In addition the whole
corsusage in yourNode.jsapplication could be simplified by not passingoptionsobject (if you are currently only testing things out in development) and falling back todefaultsettings which will enable content for allorigins.