使用 CORS 在 React 中获取问题 [英] Trouble with Fetch in React with CORS

查看:39
本文介绍了使用 CORS 在 React 中获取问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

使用 CORS 响应 Fetch(端口 3000)

React Fetch (port 3000) with 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.我错过了什么?

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?

回复:

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() 转换 fetch 响应.它返回一个承诺,所以你可以这样使用它:

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

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.

这篇关于使用 CORS 在 React 中获取问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆