Angular Cli Http Get call由于CORS问题而工作但不是Http Post

时间:2018-01-04 11:28:47

标签: angular cors angular-cli

我是angular cli的新手并试图将一个角度cli应用程序连接到我的java servlet。我正在使用@ angular / cli:1.6.2版本以及节点js版本v8.9.3。

我使用https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md引用来配置代理。

下面的

是我的httpservice类中的函数调用

 public authentication(email, password) {
    console.log("GET WITH HEADERS");
    let headers = new Headers(
      {
        'Access-Control-Allow-Origin': '*',
        'access-control-allow-methods': 'POST, GET, OPTIONS, PUT, DELETE, HEAD',
    'Access-Control-Request-Headers': 'x-requested-with
      }
    );
    let options = new RequestOptions({ headers: headers });


    return this.http.post('http://192.168.1.6:8080/Observer/GetJson', {
      email: email,
      password: password
    }, options).map(
      (response) => response.json()
      )
      .subscribe(
      (data) => console.log(data)
      )
  }
下面的

是proxy.conf.json

{
    "/Observer/*": {
        "target": "http://192.168.1.6:8080",
        "secure": false,
        "pathRewrite": {
            "^/Observer": "http://192.168.1.6:8080/Observer"
        },
        "changeOrigin": true
    }
}

我在package.json文件中添加了这一行:

“start”:“ng serve --proxy-config proxy.conf.json”

下面是提供数据的java servlet:

package com;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.javafaker.Faker;
import com.google.gson.Gson;

import data.Person;

/**
 * Servlet implementation class GetJson
 */
@WebServlet("/GetJson")
public class GetJson extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public GetJson() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = params.nextElement();
            System.out.println("Parameter Name - " + paramName + ", Value - " + request.getParameter(paramName));
        }

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
        }
        Faker faker = new Faker();
        List<Person> personArray = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Person p = new Person(faker.name().fullName(), faker.address().fullAddress(),
                    faker.phoneNumber().cellPhone(), faker.number().numberBetween(1, 1000), faker.book().genre());
            personArray.add(p);
        }
        System.out.println(new Gson().toJson(personArray));
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");

        response.getWriter().append(new Gson().toJson(personArray));
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

但不知何故Get call正在运行,但Post无效并显示如下错误:

Failed to load http://192.168.1.6:8080/Observer/GetJson: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.6:4200' is therefore not allowed access.

1 个答案:

答案 0 :(得分:0)

您正在使用angular-cli proxy,但您仍在向服务器发送http请求:

return this.http.post('http://192.168.1.6:8080/Observer/GetJson', {

您应该将该网址更改为/Observer/GetJson,以便通过angular-cli代理进行路由:

return this.http.post('/Observer/GetJson', {

因此请求localhost:4200/Observer/GetJson - 这将有助于您解决CORS。

还要记住,这仅用于开发。对于生产用途,您需要一些nginx或路由来将服务器端点映射到同一个域/端口。