Angular Cli Http Get call Working but not Http Post call due to CORS issue

Feroz Siddiqui Source

I am new to angular cli and trying to connect a angular cli application to my java servlet. I am using @angular/cli: 1.6.2 version alongwith node js version v8.9.3.

I have conifgured proxy using https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md reference.

below is my function call in my httpservice class

 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)
      )
  }

below is the proxy.conf.json

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

i have add this line in my package.json file :

"start": "ng serve --proxy-config proxy.conf.json"

below is java servlet which provide data :

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);
    }

}

but somehow Get call is working but Post is not working and displaying error as below :

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.
angularcorsangular-cli

Answers

answered 9 months ago Martin Nuc #1

You are using angular-cli proxy and still you are making http request directly to your server:

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

You should really change that url to something like /Observer/GetJson so it gets routed through angular-cli proxy:

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

So request will be made to localhost:4200/Observer/GetJson - this will help you solve CORS.

Also remember that this is used only for development. For production use you will need some nginx or routing to map your server endpoint to the same domain/port.

comments powered by Disqus