我正在写一个CRUD应用程序使用泽西和React.js前端的Glassfish 4.0。我的应用程序类:
@ApplicationPath("API")
public class AppServ extends Application
{
@Override
public Set<Class<?>> getClasses()
{
Set<Class<?>> classes = new HashSet<>();
classes.add(RestRoot.class);
classes.add(JacksonFeature.class);
return classes;
}
@Override
public Set<Object> getSingletons()
{
Set<Object> out = new HashSet<>();
out.add(new CorsFilter());
return out;
}
}
我的CORS过滤器:
@Provider
@Priority(Priorities.HEADER_DECORATOR)
public class CorsFilter implements ContainerResponseFilter
{
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException
{
responseContext.getHeaders().add(
"Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add(
"Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add(
"Access-Control-Allow-Headers",
"origin, content-type, accept, authorization, cookie");
responseContext.getHeaders().add(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
由我的前端执行的fetch:
fetch("MY_SERVER_IP:8080/FitAppBackend/API/food", {
method: 'PUT',
credentials: 'include',
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
'User-Agent': ''
},
body: JSON.stringify({
name: this.state.fName,
cals: this.state.cals,
prot: this.state.prot,
carbs: this.state.carbs,
fat: this.state.fat
})
});
当我用Postman测试API时,我得到了一个204的响应,但上面的fetch给了我一个403。我怀疑这与我的CORS过滤器有关,或者是因为我的浏览器使用PUT发送了一个G_ENABLED_IDPS=google cookie。任何帮助都将不胜感激;我已经试着解决这个问题好几个小时了。
发布于 2020-11-22 09:57:07
Access-Control-Allow-Headers
响应头的目的是告诉浏览器允许对请求使用哪些请求头。您拥有的列表如下:origin, content-type, accept, authorization, cookie
。但在您的请求中,您正在尝试设置User-Agent
标头。如果您删除标题或将其添加到列表中,它应该可以工作。
另请参阅:
https://stackoverflow.com/questions/64921034
复制