我对CORS完全陌生,我遇到了以下问题:
- 我正在使用create-react-app(端口3000),它调用在spring Boot (端口8080)中创建的一些REST服务。我将JWT auth添加到我的REST API中,所以现在我必须在调用其他任何东西之前进行身份验证。
问题是,我可以在我的SpringBoot项目index.html(我用来测试jwt auth)中进行身份验证,但现在我在React上调用/auth POST,我得到了200 OK,但我似乎无法在响应中找到Token。
SpringBoot index.html
function doLogin(loginData) {
$.ajax({
url: "/auth",
type: "POST",
data: JSON.stringify(loginData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
setJwtToken(**data.token**); //I can get the token without a problem
$login.hide();
$notLoggedIn.hide();
showTokenInformation();
showUserInformation();
},....
React Fetch(端口3000)与CORS
fetch(url, {
crossDomain:true,
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
username: user,
password: pass,
})
}).then((responseJson) => {
console.log(responseJson);
const tokenInfo = this.state.token;
if(tokenInfo !== undefined)
.....
当react fetch返回200 OK时,我得到了一个繁琐的响应,并且似乎无法像没有CORS时那样获得responseJson.token。我错过了什么?
回复:
Response {type: "cors", url: "http://localhost:8080/auth", redirected: false, status: 200, ok: true, …}
任何帮助都欢迎。
先谢谢你了。豪尔赫
编辑:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
//.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// allow anonymous resource requests
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js"
,"/rates/**"
).permitAll()
//Allows the user to authenticate
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity
.headers()
.frameOptions().sameOrigin()
.cacheControl();
}
1条答案
按热度按时间3pvhb19x1#
您应该首先使用
.json()
转换fetch响应。它返回一个promise,所以你可以这样使用它:参见https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch。