I'm new to React - I'm trying to set up my login system to link up to my api. I'm trying to make a call from my React Redux app to my .NET core (3.1) API. My react app is on http://localhost:3000, and my api is on https://localhost:44383/ (not sure if that matters).
I'm getting the following cors error when making a POST.
I don't think the problem is from the api because I've setup my policy for cross origin requests in my startup.cs ConfigureServices method (C#)
services.AddCors(options =>
{
options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
options.AddPolicy(name: "react",
builder =>
{
builder.WithOrigins("http://localhost:3000/").WithHeaders(HeaderNames.AccessControlAllowOrigin, "http://localhost:3000"); ;
});
});
and used that policy in the configure method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("react");
app.UseAuthentication();
app.UseAuthorization();
app.UseAuth();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
And I can see from a request in postman that the correct header is being attached:
I'm less familiar with react - but these are the parts of my auth which contains the call to the api with headers:
loginEffect() function of AuthSaga.ts (React/Typescript)
export function* loginEffect(action: any) {
console.log("loginEffect", action)
try {
const data = {
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3000/"
},
body: {
...action.payload,
},
}
const { timeoutDelay, response } = yield race({
timeoutDelay: delay(10000),
response: call(AuthAPI.postLogin, data),
})
if (timeoutDelay) {
yield put(setAuthFailure("Server timed out"))
}
if (response) {
if (response.status === 200) {
console.log("200");
const responseJson = yield response.json()
yield put(loginSuccess(responseJson))
} else {
console.log("fail");
const responseJson = yield response.json()
yield put(setAuthFailure(responseJson))
}
}
} catch (error) {
yield put(setAuthFailure("Something went wrong. Try again later."))
}
}
login.tsx
export const Login: React.FC = (props) => {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const dispatch = useDispatch()
const handleSubmit = () => {
dispatch(login({ UserName: username, Password: password }))
}
return (
<PageWrapper>
<LoginWrapper>
<input
placeholder="Username"
onChange={(e) => setUsername(e.target.value)}
></input>
<input
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
></input>
</LoginWrapper>
<button onClick={handleSubmit}>Submit</button>
</PageWrapper>
)
}
and AuthAPI.ts
export const AuthAPI: AuthAPIInterface = {
async postLogin(data: any): Promise<object> {
const postLoginUrl: string = `${ baseApi.authUrl }/login`
console.log('[URL FOR postLogin]', postLoginUrl);
console.log(data);
return fetch(postLoginUrl, {
method: 'POST',
headers: data.headers,
credentials: 'include',
body: JSON.stringify(data.body)
})
},
async postRegister(data: any): Promise<object> {
const postRegisterUrl: string = `${ baseApi.authUrl }/register`
console.log('[URL FOR postRegister]', postRegisterUrl);
return fetch(postRegisterUrl, {
method: 'POST',
headers: data.headers,
credentials: 'include',
body: JSON.stringify(data.body)
})
}
question from:
https://stackoverflow.com/questions/65598877/getting-this-cors-error-on-my-react-app-when-calling-my-api-no-access-control