简体   繁体   English

播放带有响应前端的Java后端框架不会返回正确的http响应

[英]Play framework java backend with react front end doesnt return proper http response

Below has my application.conf file. 下面有我的application.conf文件。 And note that the reason, there are several lines is, I have tried several combinations to fix the issue. 并请注意,原因有几行,我尝试了几种组合来解决此问题。 But could not find any fix. 但是找不到任何修复。

Fetch API call in React front end 在React前端获取API调用

fetch('http://localhost:9000/items', {
        method: 'GET'
}).then(
    response => response.json()
).then(
    data => {
        console.log(data);
    }
).catch(
    error => {
        console.error(error);
        console.log('errr');
    }
);

Application.conf file Application.conf文件

play.filters.hosts {
   allowed = ["."]
}
play.filters.disabled += "play.filters.headers.SecurityHeadersFilter"
play.filters.disabled += play.filters.cors.CORSFilter
play.filters.disabled += play.filters.csrf.CSRFFilter
play.filters.headers.contentSecurityPolicy = "default-src 'self'; img-src 'self' https://my.img.cdn.com"
# disable the built in filters
# play.http.filters = play.api.http.NoHttpFilters
play.filters.enabled += "play.filters.cors.CORSFilter"
play.filters.cors {
  # allow all paths
  pathPrefixes = ["/"]
  # allow all origins (You can specify if you want)
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  # allow all headers
  allowedHttpHeaders = ["Accept", "Content-Type"]

Below image shows the options request which react front end requests. 下图显示了响应前端请求的选项请求。

响应前端请求的选项请求

Also below are the errors and warnings in the console. 下面也是控制台中的错误和警告。

CORS

Then checked with removing headers in http request. 然后检查是否删除了http请求中的标头。 Then Got 200 by sending a GET request in the network tab. 然后,通过在网络标签中发送GET请求获得200。 But thrown an exception in the fetch api call 但是在获取api调用中引发了异常 没有标题

So it should be a cors issue in the play API it seems. 因此,看来在play API中应该是cors问题。 But could not figure it out by doing different changes in application config. 但是无法通过对应用程序配置进行不同的更改来弄清楚。

I have fixed the issue and below will be the answer. 我已经解决了这个问题,下面将给出答案。

play.filters.enabled += "play.filters.cors.CORSFilter"

play.filters.cors {
  allowedOrigins = ["http://localhost:8080", "http://localhost:9000"]
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  preflightMaxAge = 3 days
}

Hope this will be helpful for anyone. 希望这对任何人都有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM