0

I am new from here. Just stuck on some problem of fetching the data from frontend(react) to the raw value in JSON. For the login part, when I enter the email and password, supposedly the response are same as the result in POSTMAN, but i get the error. I am figure out this issue for almost one week. I would be appreciate for those who help me to solve on this issue. I will elaborate further on below about my situation:

Here is the response of API from Postman (supposedly I should get this response): The response of API from POSTMAN

The result I get in the browser:

enter image description here

Source Code:

constructor (props){
  super(props);
  this.state ={
    loginEmail: '',
    loginPassword: ''
  }
  this.login = this.login.bind(this);
  this.onChange = this.onChange.bind(this);
}

login(){
  PostData('api/users/login', this.state).then ((result) => {
    let responseJSON = result;
    console.log(responseJSON);
  });
}

PostData:

export function PostData(type, userData = {}){

    let BaseUrl = "https://ems-unimas-58134.herokuapp.com/"
    
    return new Promise((resolve, reject) => {

        fetch(BaseUrl+type,{
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // headers:{
            //   'Content-Type': 'application/json'
            // }
          }).then(res => res.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });

}

Commend down here if anyone of you need more code.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
koko ka
  • 107
  • 4
  • 17
  • uncomment the headers property. You can see which headers postman is using by clicking the Headers tab – AngelSalazar Jan 13 '20 at 15:08
  • Hi, @AngelSalazar thanks for comment here. But if I uncomment the headers, This error comes out "Access to fetch at 'https://ems-unimas-58134.herokuapp.com/api/users/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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." – koko ka Jan 13 '20 at 15:13
  • 1
    In postman, you can copy the script as fetch [can you see this](https://stackoverflow.com/questions/49432735/converting-a-postman-request-to-curl) – Julio Javier Jan 13 '20 at 15:15
  • @kokoka then the problem is your server, you have to whitelist localhost – AngelSalazar Jan 13 '20 at 15:17

1 Answers1

0

The problem is you need to allow CORS. You can read more about CORS in here

Snirjka
  • 315
  • 2
  • 5