Request fails due to CORS issue with origin from localhost

旧街凉风 提交于 2019-12-30 06:38:19

问题


I have seen dozens of questions on SO and different blogs talking about this with "answers" -- all to no avail.

I have a React.js app on my local machine (Ubuntu 16.04). Locally, I try to test it by running npm start and it opens up the browser to http://localhost:3000.

On one page, I am trying to access my PHP api which is on my shared hosting server.

Chrome and Firefox both say that it fails due to server not having Access-Control-Allow-Orgin.

Exact Message:

Failed to load http://---/api/v1/categories: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost.com:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
localhost.com/:1 Uncaught (in promise) TypeError: Failed to fetch

However, upon my php server entry point I do have:

header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");

Here is where I make my api call in my react app:

 componentDidMount() {

  var options = {
    method: 'get',
    headers: {
        "Access-Control-Request-Headers": "*",
        "Access-Control-Request-Method": "*"
    },
  }

  // I have since removed the headers from the options as advised in the comments 
  fetch('http://---/api/v1/categories', options)
  .then(results => {
    return results.json();
  }).then(data => {
    let categories = data.map((category) => {
      return(
        // edited out
      )
    })
    this.setState({categories: categories});
  })
 }
}

I have tried this on both Chrome and Firefox; I have also tried to alias my server away from localhost. I have tried the no-cors approach, which does get me access -- but breaks everything of course. I have tried with and without passing headers along with my fetch request.

UPDATE:

I did get it to work by installing this Chrome plugin. I feel this is a workaround and would like to know if there is a coding answer here.


回答1:


I'm an idiot.

Origin was misspelled as Orgin.

This typo has existed in my project for almost three years. This was the first time I needed to use cross-domain access.




回答2:


header("Access-Control-Allow-Methods: *");

Should be:

header("Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH");

...and any other methods you intend to accept.



来源:https://stackoverflow.com/questions/48955928/request-fails-due-to-cors-issue-with-origin-from-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!