java - 从 localhost:4200 访问 localhost:8080 的 XMLHttpRequest 已被 CORS 策略阻止
问题描述
“从源 'http://localhost:4200' 访问 XMLHttpRequest 在 'http://localhost:8080/authenticate/login' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:确实没有 HTTP 正常状态。”
Spring Boot 后端,Angular 前端。尝试以包含用户名和密码的登录对象的形式发送 Http 帖子。它应该收到一个 jwt 令牌作为回报。在邮递员中完美运行,所以它让我相信谷歌浏览器是问题所在。我也在使用 Allow CORS Chrome 扩展。
奇怪的是,http GET 请求有效。
我尝试用角度制作代理,但没有解决问题。我也可能做错了,我是制作网络应用程序的新手,所以一些网站上所有模糊的说明真的让我很沮丧。
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")
到控制器方法应该可以解决您的问题。查看为 RESTful Web 服务启用跨源请求
推荐阅读
- java - 如何修复 SSLHandshakeException:无效的 CertificateVerify 签名
- python - 如何在熊猫中进行部分数据帧转置
- autodesk-forge - Forge BIM 360 资产 API
- ruby-on-rails - 在rails activeadmin中对多个连接table_for进行排序
- c# - 单元测试失败
- python - 使用 numpy 制作一维数组 2D
- c++ - C++:我在一种方法中得到一个迭代器,如何在另一种方法中通过迭代器修改原始列表?
- node.js - 无法识别正确的 PostgreSQL 代码(node.js 服务器)
- node.js - Dialogflow 实现在 5 秒后超时,我们如何克服这个限制?
- c# - 使用 | 具有属性的运算符