简体   繁体   中英

Access to fetch at 'http://example.com/myApi' from origin 'http://localhost:3000' has been blocked by CORS policy in ReactJs

We are trying to call Web API using reactJs but getting error Access to fetch at 'http://example.com/myApi' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. in ReactJs Access to fetch at 'http://example.com/myApi' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. in ReactJs

We are using ASP.Net WEB API and we have allowed cors origin from web and controller but still we are getting error.

My Code:-

 class List extends Component{ constructor(props) { super(props); this.state={ listItem: [], isSuccess: false } } componentDidMount(){ fetch('http://example.com/myApi',{ 'headers':{ 'Content-Type':'application/json', 'Token':'PrimaryAuth' }, }).then(res => res.json()).then(data => { console.log(data) this.setState({ listItem: data }) }) } render() { var { isSuccess, loginItems} = this.state; if(.isSuccess){ return <div>Not Loading...</div> } else{ return( <div className="List"> <ul> {loginItems.map(item =>( <li key={item.message}> {item.message} </li> ))} </ul> </div> ) } } }

Error screenshot:- 在此处输入图像描述

This doesn't have anything to do with React.

If you look in the error that you're getting it states that the preflight request (which is an OPTIONS request) has not returned with a response status of OK (200).

So I'm assuming you haven't actually implemented CORS correctly on your web server as you need to allow for an OPTIONS method to be made and respond with 200 to it.

I suggest you look more into CORS and how to handle it correctly: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM