I'm facing a problem, for some reason my API failed to fetch. The server side is on C# and SQL, everything works fine there, but when I am trying to connect between them on React, it fails. my local host url is : http://localhost:50434/api/users
My code is:
var url = "http://localhost:50434/api/users";
btnLogin = async () => {
console.log(1);
console.log(this.state.EmailValue "," this.state.PasswordValue);
let s = await this.checkUserDetails(
this.state.EmailValue,
this.state.PasswordValue
);
console.log("returned value=" s);
if (s != null) {
this.setState({ user_id: s.user_id });
console.log("user_id is =" this.state.user_id);
this.setState({ showErrLbl: false }, () => {
this.props.history.push({
pathname: "/DrawPage/",
state: { UserObj: s }
});
});
console.log("h1");
} else {
console.log("err login!");
this.setState({ showErrLbl: true });
} };
checkUserDetails = async (Email, Password) => {
let returnedObj = null;
console.log("we are in func checkUserDetails, email = " Email);
await fetch(url `?email=${Email}&pass=${Password}`, {
method: "GET", // 'GET', 'POST', 'PUT', 'DELETE', etc.
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json",
}),
}) // Call the fetch function passing the url of the API as a parameter
.then((resp) => resp.json()) // Transform the data into json
.then(function (data) {
console.log("meow");
console.log(data);
if (data != null) {
console.log(data.Email);
console.log(data.Password);
returnedObj = data;
} else {
console.log("wrong email or password!");
returnedObj = null;
}
})
.catch(function (err) {
alert(err);
});
return returnedObj;
};
Thanks for all the helpers
CodePudding user response:
You must enable Cross-Origin Requests (CORS) in your server-side project, read this guide about it:
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
CodePudding user response:
In your package.json set
"proxy": "http://localhost:50434/"
and call fetch omitting the host part.
var url = '/api/users'