[英]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.