Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have some problems with sending a POST request to my REST-API.

The problem is, when I send it from a react application, it shows me this error in the debug console of firefox.

The funny thing is, that it works perfectly fine when sending the request with postman.

This is the code i use to make the request:

let apiURL = API_URL_BASE + "/api/authenticate"
        let requestBody = JSON.stringify(
            {
                "username": this.getEnteredLoginUsername(),
                "password": this.getEnteredLoginPassword()
            }
        );
        let headerData = new Headers();
        headerData.append('Accept', '*');
        headerData.append("Access-Control-Allow", "*");
        headerData.append('Content-Type', 'application/json');
        headerData.append('Access-Control-Allow-Origin', '*');
        headerData.append("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        headerData.append("Access-Control-Allow-Headers", "*");
        
        let requestOptions = {
            method: 'POST',
            mode: 'cors',
            redirect: 'follow',
            body: requestBody,
            headers: headerData
        }
        this.setState({loadingData: true});
        fetch(apiURL, requestOptions).then( response => {
            let responseStatus = response.status;
            response.json().then( responseJSON => {
            });
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
891 views
Welcome To Ask or Share your Answers For Others

1 Answer

You do seem to have a correct request header from the client-side, i.e the browser, but your server that is hosting the API must also send a response to the client back indicating that it allows cross-origin requests, Otherwise browser would not proceed ahead with your request. Setting cors headers from the server would depend on what framework you're using for the backend. In fact you need to add those cors header you've added here to the server code.

A sample response header would look like this :

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2
Access-Control-Allow-Origin: * (Note: * means this will allow all domains to request to your server)
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml

For express, you can follow this link.

More on CORS here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...