javascript - 在使用 CORS 的 React 中获取问题

标签 javascript reactjs spring-boot cors fetch-api

我是 CORS 的新手,我遇到了以下问题:

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

事情是,我可以在我的 SpringBoot 项目 index.html 中进行身份验证(我用来测试 jwt 身份验证),但是现在我在 React 上调用/auth POST,我得到了 200 OK 但我似乎找不到响应中任何位置的 token 。

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(端口 3000)与 CORS

    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)
.....

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

响应:

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

欢迎任何帮助。

提前致谢。 豪尔赫

编辑:

@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();
}

最佳答案

您应该首先使用 .json() 转换获取响应。它返回一个 promise ,所以你可以这样使用它:

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) {
...

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

关于javascript - 在使用 CORS 的 React 中获取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48562406/

相关文章:

javascript - 为什么 ajax 调用中的闭包可以访问外部范围?

javascript - 如何在爱彼迎 react 日期中选择小时/分钟

java - 为什么无法解析我的 com.vaadin.UI 导入?

java - 无法使用 Spring Boot 测试测试 MockMultipartFile - 找不到序列化器

java - 使用 LocalDate 类型参数发送请求

javascript - Jquery 菜单在移动浏览器中不起作用

javascript - useCallback 与简单函数

javascript - 碰撞检测在吃 bean 人游戏中不起作用

reactjs - react-konva 如何设置舞台宽度和高度等于其容器?

javascript - 使用 React State 和 UseEffect 控制输入字段焦点