Reputation: 1309
I am new in react. I am using jwt authentication in react. The login api is working fine in post man. I use tha api url and trying to post the data from react but it says -
Access to fetch at 'http://localhost:3000/' (redirected from 'http://127.0.0.1:8000/api/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is source code:
import {memo} from 'react'
import React, { Component } from 'react'
export default class Test extends Component {
constructor(){
super();
this.state= {
email:null,
password:null,
}
}
login(){
console.log(this.state);
fetch('http://127.0.0.1:8000/api/login',{
method:'POST',
body: JSON.stringify(this.state)
}).then((res)=>res.json().then((result)=>{console.log(result)}))
}
render() {
return (
<div>
<input type='email' placeholder='email' onChange={(e)=>{this.setState({email:e.target.value})}}/><br/>
<input type='password' placeholder='password' onChange={(e)=>{this.setState({password:e.target.value})}}/>
<button type='button' onClick={()=>{this.login()}}>Login</button>
</div>
)
}
}
How to fix it?
Upvotes: 1
Views: 669
Reputation: 420
This is called CORS error. Basically, your app is requesting resource that is on different origin compared to your web app. In order to fix this you have to whitelist this domain in your server by using Access-Control-Allow-Origin
or you need to enable CORS in your server.
Upvotes: 1