Javascript 使用 CORS 在 React 中获取问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48562406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:09:50  来源:igfitidea点击:

Trouble with Fetch in React with CORS

javascriptreactjsspring-bootcorsfetch

提问by J_Ocampo

I'm completely new to CORS and i'm having the following issue:

我对 CORS 完全陌生,我遇到了以下问题:

-I'm using create-react-app (port 3000) that invokes some REST Services made in spring boot (port 8080). I added JWT auth to my REST API so now i have to authenticate before i call anything else.

-我正在使用 create-react-app(端口 3000)调用一些在 spring boot(端口 8080)中创建的 REST 服务。我将 JWT 身份验证添加到我的 REST API,所以现在我必须在调用其他任何东西之前进行身份验证。

Thing is, i can authenticate in my SpringBoot project index.html (which i used to test the jwt auth), but now that i call the /auth POST on React, i get a 200 OK but i cant seem to find the Token anywhere in the response.

事情是,我可以在我的 SpringBoot 项目 index.html(我用来测试 jwt auth)中进行身份验证,但是现在我在 React 上调用 /auth POST,我得到 200 OK 但我似乎无法在任何地方找到令牌在回应中。

SpringBoot index.html

SpringBoot index.html

function doLogin(loginData) {
        $.ajax({
            url: "/auth",
            type: "POST",
            data: JSON.stringify(loginData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                setJwtToken(**data.token**); //I can get the token without a problem
                $login.hide();
                $notLoggedIn.hide();
                showTokenInformation();
                showUserInformation();
            },....

React Fetch (port 3000) with CORS

使用 CORS 响应 Fetch(端口 3000)

    fetch(url, {
      crossDomain:true,
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({
        username: user,
        password: pass,
      })
    }).then((responseJson) => {
      console.log(responseJson);
      const tokenInfo = this.state.token;

      if(tokenInfo !== undefined)
.....

While the react fetch returns a 200 OK, i get a fussy response and cant seem to get the responseJson.token the same way that i did without CORS. What am i missing?

虽然 react fetch 返回 200 OK,但我得到了一个挑剔的响应,并且似乎无法像没有 CORS 时那样获得 responseJson.token。我错过了什么?

Response:

回复:

Response {type: "cors", url: "http://localhost:8080/auth", redirected: false, status: 200, ok: true,?…}

Any help is welcome.

欢迎任何帮助。

Thanks in advance. Jorge

提前致谢。乔治

EDIT:

编辑:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

            // allow anonymous resource requests
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
                    ,"/rates/**"
            ).permitAll()
            //Allows the user to authenticate
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity
            .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity
            .headers()
            .frameOptions().sameOrigin()
            .cacheControl();
}

回答by Miguel Calderón

You should convert the fetch response first with .json(). It returns a promise, so you can use it this way:

您应该首先使用.json(). 它返回一个承诺,所以你可以这样使用它:

fetch(url, {
  crossDomain:true,
  method: 'POST',
  headers: {'Content-Type':'application/json'},
  body: JSON.stringify({
    username: user,
    password: pass,
  })
})
  .then(response => response.json())
  .then(responseJson => {
    console.log(responseJson);
    const tokenInfo = this.state.token;
    if (tokenInfo !== undefined) {
...

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch