angularrestpostpostmanhacker-news-api

Check login credentials of remote website with Angular


I'm creating an interface for hackers news with angular 7. Normally I use the public APIs available, but for login services they are not available.

I'm trying to make a POST call, as done by an OpenSource Android Client app for HN, specifically in this file: https://github.com/hidroh/materialistic/blob/master/app/src/main/java/io/github/hidroh/materialistic/accounts/UserServicesClient.java to the url https://news.ycombinator.com/login , setting the username, password and redirect as parameters.

Unfortunalty my request is blocked by the CORS policy.

I performed the test with Postman and instead works perfectly.

This is my code:

const payload = {
  'acct': 'username',
  'pw': 'password',
  'goto': 'news'
};

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE, HEAD',
    'Access-Control-Allow-Headers': 'X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept',
    'Access-Control-Allow-Access-Control-Max-Age': '1728000',
  })
};

console.log('Try login');
this.http.post('https://news.ycombinator.com/login', payload, httpOptions)
  .pipe(
    tap(
      data => console.log(data),
      error => console.log(error)
    )
  ).subscribe(result => console.log(result));

how could I solve?


Solution

  • The solution for CORS problems is to use a proxy, for angular, in development, you can use the Angular CLI server as a proxy (https://stackoverflow.com/questions/50021126/implementation-of-proxy-server-in -angular4-5? rq = 1).

    This is my proxy.conf.json:

    {
      "/hackernews/*": {
      "target":  {
          "host": "news.ycombinator.com",
          "protocol": "https:",
          "port": 443
      },
      "secure": false,
      "logLevel": "info",
      "changeOrigin": true,
      "pathRewrite": {"^/hackernews" : ""}
      }
    }
    

    Edit "start" of your package.json to look below

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

    Unfortunately for the actual build there is no such simple solution, a proxy can be specified on the production server, depending on the server used.