Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React app using API with another origin (CORS)

I have a react app, which uses a java ee backend rest server, running on another domain. I have enabled CORS:

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Headers : origin, content-type, accept, authorization
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age : 1209600

I am using react with fetch like this:

export function get(path, headers) {
    return fetch(apiUrl + path, {
        "metod" : "GET",
        "headers" : headers,
        "credentials" : "include"
    })
}

My react app is running on http://localhost:3000. When I am logging in, the server returns the Set-Cookie, but the cookie is not included in any further request to the server, unless I try to log in again. Then it is included for that specific login request.

Any suggestions?

like image 759
fonnes Avatar asked May 02 '17 20:05

fonnes


People also ask

Can I use CORS in React?

In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there.

Does CORS apply to APIs?

CORS is typically required to build web applications that access APIs hosted on a different domain or origin. You can enable CORS to allow requests to your API from a web application hosted on a different domain.


1 Answers

I just want to share how I make my local development painless by this post if you are using create-react-app by just adding your main API url proxy to your package.js for example "proxy": "http://localhost:8080/API" No need to setup CORS on your backend.

like image 65
praHoc Avatar answered Sep 21 '22 17:09

praHoc