具有代理重定向的角度应用程序上的错误404

时间:2019-11-11 13:40:44

标签: angular spring-boot httpclient http-proxy

我正在开发有角度的弹簧靴子应用程序。

我发出以下请求

  getListProduitImmobilierDTO(pagesize: number, page: number, search: Search): Observable<ProduitImmobilierDTO[]> {
    const headerDict = {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'Accept-Charset': 'charset=UTF-8',
      'Access-Control-Allow-Headers': 'Content-Type'
    };

    const requestOptions = {
      headers: new HttpHeaders(headerDict)
    };
    return this.http.get('/api/produitimmobilier/all/' + pagesize + '/' + page, requestOptions).pipe(map((jsonArray: any) =>jsonArray.map((jsonItem) => ProduitImmobilierDTO.fromJson(jsonItem))));

我使用以下proxy.config.json重定向请求

{
  "/api/*": {

    "target":  {
       "host": "localhost",
       "protocol": "http:",
       "port": 8080
     },
    "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
  }
}

并使用以下命令启动角度应用程序

ng serve --proxy-config proxy.config.json

在服务器端,我具有以下spring boot控制器:

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping({"/api"})
public class ProduitImmobilierController {

    Logger logger = LoggerFactory.getLogger(ProduitImmobilierController.class);

    @Autowired
    private ProduitImmobilierService produitImmobilierService;

    @RequestMapping(value = "/produitimmobilier/all/{pageSize}/{page}",
    method = RequestMethod.GET,
    produces = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE},
    consumes = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody List<ProduitImmobilierDTO> findAll(@PathVariable("pageSize") int pageSize, @PathVariable("page") int page){
        logger.info("CONTROLLER PRODUITIMMOBILIERSERVICE CA PASSE");
        return produitImmobilierService.findAll(pageSize, page);
    }

它曾经可以工作。我尝试修改了请求,撤消请求后,它不再起作用。我有以下错误

An attempt to set a forbidden header has been blocked : Accept-Charset http.js:2346
Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/produitimmobilier/all/5/1", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:4200/api/produitimmobilier/all/5/1: 404 Not Found", error: {…} }

你能帮我吗

1 个答案:

答案 0 :(得分:0)

使用Angular dev-server proxy时,不应在服务器上配置CrossOrigin,因为Angular dev-server proxy只会在您的前端应用程序运行所在的域+端口上接收浏览器请求,然后转发该请求到您的后端API服务器,在您的情况下,对端口4200的所有请求都被转发到端口8080

您正在尝试设置'Accept-Charset'标头,但根据MDN 'Accept-Charset'标头为Forbidden header name(禁止的标头名称是无法以编程方式修改的所有HTTP标头的名称)

在任何情况下都不应该使用'Accept-Charset'头,因为现在已经很好地支持UTF-8和首选的字符编码。为了通过较少的基于配置的熵保证更好的隐私,所有浏览器都省略了Accept-Charset标头:Internet Explorer 8 +,Safari 5 +,Opera 11 +,Firefox 10+和Chrome 27+不再发送。