CORS を使用した React のフェッチに関する問題 質問する

CORS を使用した React のフェッチに関する問題 質問する

私は CORS をまったく初めて使用しており、次のような問題が発生しています。

-Spring Boot (ポート 8080) で作成されたいくつかの REST サービスを呼び出す create-react-app (ポート 3000) を使用しています。REST API に JWT 認証を追加したので、他のものを呼び出す前に認証する必要があります。

問題は、SpringBoot プロジェクトの index.html (jwt 認証をテストするために使用) で認証できることですが、React で /auth POST を呼び出すと、200 OK が返されますが、応答のどこにもトークンが見つからないようです。

SpringBoot インデックス.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 を使用した React 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)
.....

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

ベストアンサー1

まず、フェッチ応答を で変換する必要があります.json()。これは Promise を返すので、次のように使用できます。

fetch(url, {
  mode: 'cors',
  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/Fetch の使用

おすすめ記事