简体   繁体   English

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

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

"Access to XMLHttpRequest at 'http://localhost:8080/authenticate/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." “CORS 策略已阻止从源 'http://localhost:4200' 在 'http://localhost:8080/authenticate/login' 访问 XMLHttpRequest:它确实没有 HTTP 正常状态。”

Spring Boot backend, Angular front. Spring 引导后端,Angular 前端。 Tried sending an Http post, in the form of a login object containing a username and password.尝试以包含用户名和密码的登录 object 的形式发送 Http 帖子。 It's supposed to receive a jwt token in return.它应该收到一个 jwt 令牌作为回报。 Works perfectly in postman, so it leads me to believe google chrome is the issue.在 postman 中完美运行,所以它让我相信谷歌浏览器是问题所在。 I'm using the Allow CORS Chrome extention as well.我也在使用 Allow CORS Chrome 扩展。

Weirdly enough the http GET requests work.奇怪的是,http GET 请求有效。

I tried making a proxy in angular which didn't fix the issue.我尝试在 angular 中制作代理,但没有解决问题。 I also might have done it wrong too, I'm new to making web applications so all the vague instructions on some websites really frustrate me.我也可能做错了,我是新来制作 web 应用程序,所以一些网站上所有模糊的说明真的让我很沮丧。

auth.service.ts Which sends the request 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 Which receives the request 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);
        }
    }

}

I'm sorry in advance for my lack of basic knowledge on the subject.我很抱歉我缺乏这方面的基本知识。

adding @CrossOrigin(origins = "http://localhost:4200") to the controller method should solve your issue.@CrossOrigin(origins = "http://localhost:4200")添加到 controller 方法应该可以解决您的问题。 Take a look at Enabling Cross Origin Requests for a RESTful Web Service查看为 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 resource from angular app 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.

相关问题 带 Angular 的弹簧靴。 CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:8080/”处的 XMLHttpRequest - Spring boot with Angular. Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:4200' has been blocked by CORS policy CORS 策略阻止了从来源“http://localhost:3000”访问位于“http://localhost:8080/blog/updatePost/2”的 XMLHttpRequest: - Access to XMLHttpRequest at 'http://localhost:8080/blog/updatePost/2' from origin 'http://localhost:3000' has been blocked by CORS policy: Angular 6 + Spring Boot:错误:“来自源‘http://localhost:4200’已被 CORS 策略阻止” - Angular 6 + Spring Boot: Error: "from origin 'http://localhost:4200' has been blocked by CORS policy" 来自源“http://localhost:4200”的“http://localhost:8888/mydomain/path”已被 CORS 策略阻止:不存在“访问控制允许源” - 'http://localhost:8888/mydomain/path' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' is present 'http://localhost:4200' 已被 CORS 策略阻止:请求的资源上不存在'Access-Control-Allow-Origin' header - 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 策略阻止了从源“http://localhost:3000”获取“http://localhost:9900/jaxrs-post-example/rest/customers”的访问权限 - Access to fetch at 'http://localhost:9900/jaxrs-post-example/rest/customers' from origin 'http://localhost:3000' has been blocked by CORS policy CORS 策略已阻止从源访问 XMLHttpRequest:对预检请求的响应未通过访问控制检查: - Access to XMLHttpRequest from origin has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 将 Angular 连接到 Spring 的 CORS 错误(localhost 8080 &lt;--&gt; localhost 4200) - CORS error connecting Angular to Spring (localhost 8080 <--> localhost 4200) 尽管 Controller 启用了 Crossorigin 并设置了 Header,但对 XMLHttpRequest 的访问已被 CORS 策略阻止 - Access to XMLHttpRequest has been blocked by CORS policy eventhough Controller has Crossorigin enabled and Header set Spring 安全 CORS:来源已被 CORS 策略阻止 - Spring Security CORS: Origin has been blocked by CORS Policy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM