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

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c# - Getting this CORS error on my react app when calling my API - No 'Access-Control-Allow-Origin' header is present on the requested resource

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.

CORS error


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: headers


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

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

1 Answer

0 votes
by (71.8m points)

You have an error in:

builder.WithOrigins("http://localhost:3000/").WithHeaders(HeaderNames.AccessControlAllowOrigin, "http://localhost:3000"); 

remove the last "/" from origins:

builder.WithOrigins("http://localhost:3000")

and try to use all headers and metods:

options.AddPolicy(name: "react",
                  builder =>
                  {
                      builder.WithOrigins("http://localhost:3000")
                   .AllowAnyMethod()
                   .AllowAnyHeader());
                  });

Since you have two policies, you will have to add name of cors policy to your controller action, but I think for the start just remove or comment "AllowAll" policy from your startup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...