繁体   English   中英

CORS 策略已阻止从 localhost:4200 在 localhost:8080 访问 XMLHttpRequest

[英]Access to XMLHttpRequest at localhost:8080 from localhost:4200 has been blocked by CORS policy

“CORS 策略已阻止从源 'http://localhost:4200' 在 'http://localhost:8080/authenticate/login' 访问 XMLHttpRequest:它确实没有 HTTP 正常状态。”

Spring 引导后端,Angular 前端。 尝试以包含用户名和密码的登录 object 的形式发送 Http 帖子。 它应该收到一个 jwt 令牌作为回报。 在 postman 中完美运行,所以它让我相信谷歌浏览器是问题所在。 我也在使用 Allow CORS Chrome 扩展。

奇怪的是,http GET 请求有效。

我尝试在 angular 中制作代理,但没有解决问题。 我也可能做错了,我是新来制作 web 应用程序,所以一些网站上所有模糊的说明真的让我很沮丧。

auth.service.ts发送请求

import { Injectable, ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__ } from "@angular/core";
import { BehaviorSubject, Observable } from "rxjs";
import { map } from "rxjs/operators";
import { environment } from "src/environments/environment";

@Injectable({ providedIn: 'root' })
export class AuthService {

    isAuthenticatedSubject = new BehaviorSubject<boolean>(false);

    constructor(private httpClient: HttpClient) { }

    login(username: string, password: string): Observable<any> {
        const data = {
            username: username,
            password: password
        };
        let headers = new HttpHeaders();
        headers.set('Contact-Type', 'application/json'); 

        const url = `${environment.AUTH_ROUTE}`;
        return this.httpClient.post<any>(url, data, { headers: headers })
            .pipe(
                map(response => {
                    localStorage.setItem('token', response.token);
                    this.isAuthenticatedSubject.next(true);
                    return response;
                })
            );
        // { token: "vrijednost-tokena" }
    }

    logout() {
        localStorage.removeItem('token');
        this.isAuthenticatedSubject.next(null);
    }
}

AuthController.java接收请求


import com.example.stevan.madsapp.security.jwt.JwtTokenProvider;
import com.example.stevan.madsapp.web.dto.LoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/authenticate", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping(value = "/login")
    public ResponseEntity<Object> login(@RequestBody LoginDTO loginDTO)
    {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginDTO.getUsername(), loginDTO.getPassword()
        );
        try
        {
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            String token = jwtTokenProvider.createToken(authentication);
            Map<String, String> responsePayload = new HashMap<>();
            responsePayload.put("token", token);

            return new ResponseEntity<>(responsePayload, HttpStatus.OK);
        }catch (Exception e)
        {
            return new ResponseEntity<>("Error while login", HttpStatus.UNAUTHORIZED);
        }
    }

}

我很抱歉我缺乏这方面的基本知识。

@CrossOrigin(origins = "http://localhost:4200")添加到 controller 方法应该可以解决您的问题。 查看为 RESTful Web 服务启用跨域请求

it is not solving for Delete request, but it works for put and the others, I added the cross origin as follows https://gyazo.com/e058904cb5ee27685fac4f3811b9b2a8 but getting this https://gyazo.com/7481236f8ed7fcdecd2c898227c90e08 while trying to delete the来自 angular 应用程序的资源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM