我的角度代码
intercept(req: HttpRequest<any>, next: HttpHandler) {
const nextReq = req.clone({
headers: req.headers.set('Cache-Control', 'no-cache')
.set('Pragma', 'no-cache')
.set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')
.set('If-Modified-Since', '0')
.set('Authorization', 'secret')
.set('client-id', 'test')
});
return next.handle(nextReq).timeout(220000).catch(this.handleError);
}
我的Java服务代码:
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler)
{
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, Access-Control-Allow-Origin,cache-control,client-id,expires,if-modified-since, pragma");
String clientId = request.getHeader("client-id");
}
运行该应用程序后,出现此错误,并且客户端ID为空- 已被CORS政策阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态
我已经添加了所有必需的标题。
请帮助
下面是我的网络通话
答案 0 :(得分:0)
问题可能出在服务器端(您的后端),但是您可以尝试以明确的方式进行操作。 您是否愿意尝试注入可以为您提供cros配置的bean:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.GenericFilterBean;
public class CORSFilter extends GenericFilterBean implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chaine)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse)response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "*");
httpResponse.setHeader("Access-Control-Allow-Headers", "*");
httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
System.out.println("****************** CORS Configuration Completed *******************");
chaine.doFilter(request, response);
}
}
在主类中,尝试像这样注入Bean:
@Bean
public FilterRegistrationBean crosFilterRegistration(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CORSFilter());
registrationBean.setName("CORS Filter");
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(1);
return registrationBean;
}
希望这对您或其他任何人都有用:)