1

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.
Feroz Siddiqui
  • 3,840
  • 6
  • 34
  • 69
  • Possible duplicate of [How to get a cross-origin resource sharing (CORS) post request working](https://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working) – Lazar Ljubenović Jan 04 '18 at 11:37
  • i am not using jquery here also i am adding the header Access-Control-Allow-Origin in module file – Feroz Siddiqui Jan 04 '18 at 11:40
  • The reason still remains the same, with or without jQuery. Read to understand the issue, not to copy/paste code. – Lazar Ljubenović Jan 04 '18 at 11:44
  • i have added the headers in response response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD"); also updated in question. GET call is working but POST is not. – Feroz Siddiqui Jan 04 '18 at 11:54
  • also i m getting http.js:1618 Refused to set unsafe header "Access-Control-Request-Headers" this error in the request – Feroz Siddiqui Jan 04 '18 at 11:57

1 Answers1

0

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.

Martin Nuc
  • 5,604
  • 2
  • 42
  • 48