“从源 'http://localhost:4200' 访问 XMLHttpRequest at 'http://localhost:8080/authenticate/login' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。”
Spring Boot 后端,Angular 前端。尝试以包含用户名和密码的登录对象的形式发送 Http 帖子。它应该收到一个 jwt 令牌作为回报。在邮递员中完美运行,所以它让我相信谷歌浏览器是问题所在。我也在使用允许 CORS Chrome 扩展。
奇怪的是 http GET 请求有效。
我尝试在 angular 中创建一个代理,但没有解决问题。我也可能做错了,我刚开始制作网络应用程序,所以一些网站上的所有模糊说明都让我感到沮丧。
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);
}
}
}
对于我缺乏这方面的基本知识,我深表歉意。
答案 0 :(得分:0)
将 @CrossOrigin(origins = "http://localhost:4200")
添加到控制器方法应该可以解决您的问题。看看Enabling Cross Origin Requests for a RESTful Web Service