Skip to content

CORS problem with http OPTIONS  #1325

@m00zi

Description

@m00zi

I have the following environment setup on my PC:

  • Nodejs version (v10.1.0)
  • Angular version Angular CLI: 6.0.1
    Node: 10.1.0
    OS: darwin x64

I have problem with nodejs in https mode only, once the https mode is enabled on nodejs, I am not able to get any response from the server for POST request, but the GET requests are fine,
but once I switched back to normal http, the POST also working fine,

I have enabled cors in my nodejs in 2 method both are not working with https, I have restarted my PC and even create new nodejs app, same issue,

here is my first method to enable cors:

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH');
        return res.status(200).json({});
    };
    next();
});

and here is the secod method for enabling cors, I have used 3rd party library:

var cors = require('cors');
app.use(cors());

The nodejs code:

'use strict';
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var fs = require('fs');

var secureOptions = {
    key: fs.readFileSync('./ssl/key.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem')
};

var server = require('https').createServer(secureOptions, app);

server.listen(3000, () => {
    console.log('server is running on port 3000')
});

app.use('/', router);


router.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH');
        return res.status(200).json({});
    };
    next();
});
    

//router.use(cors());
router.use(bodyParser.urlencoded({extended: false}));
router.use(bodyParser.json());



router.post('/login', (req, res, next) => {
    console.log(req.body);
    res.send('BODY ==> ' + JSON.stringify(req.body));
});

this is my authService in angular:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  apiUrl = 'https://127.0.0.1:3000'
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  constructor(private http: HttpClient) { }


  login(username: String, password: String): Observable<any[]> {
    return this.http.post<any[]>(this.apiUrl + '/login', {username, password}, this.httpOptions);
  }

}

this is my component:

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private authService: AuthService) {}

doLogin(f: any) {
  this.authService.login(f.username, f.password)
    .subscribe(
      (data => {
        console.log(`data ==> ${data}`);
      }),
      (error => {
        console.log(`error ==> ${JSON.stringify(error)}`);
      })
    )

}

}

this is the html:

<form #loginForm="ngForm" (ngSubmit)="doLogin(loginForm.value)">
  Usernam: <input type="text" name="username" ngModel>
  <br>
  Password: <input type="password" name="password" ngModel>
  <br>
  <button type="submit">Login</button>
</form>

this is the console output:

Angular is running in the development mode. Call enableProdMode() to enable the production mode.
zone.js:2969 OPTIONS https://127.0.0.1:3000/login 0 ()
scheduleTask @ zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
onScheduleTask @ zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:3001
proto.(anonymous function) @ zone.js:1394
(anonymous) @ http.js:1639
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:161
(anonymous) @ subscribeTo.js:21
subscribeToResult @ subscribeToResult.js:6
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub @ mergeMap.js:127
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext @ mergeMap.js:124
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next @ mergeMap.js:107
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93
(anonymous) @ scalar.js:5
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe @ Observable.js:176
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:161
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call @ mergeMap.js:80
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158
push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call @ filter.js:55
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158
push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call @ map.js:51
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158
push../src/app/app.component.ts.AppComponent.doLogin @ app.component.ts:18
(anonymous) @ AppComponent.html:1
handleEvent @ core.js:9953
callWithDebugContext @ core.js:11046
debugHandleEvent @ core.js:10749
dispatchEvent @ core.js:7415
(anonymous) @ core.js:8892
schedulerFn @ core.js:3415
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:253
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:191
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:129
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:53
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3395
push../node_modules/@angular/forms/fesm5/forms.js.NgForm.onSubmit @ forms.js:3384
(anonymous) @ AppComponent.html:1
handleEvent @ core.js:9953
callWithDebugContext @ core.js:11046
debugHandleEvent @ core.js:10749
dispatchEvent @ core.js:7415
(anonymous) @ core.js:7859
(anonymous) @ platform-browser.js:1140
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:3662
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
app.component.ts:23 error ==> {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

https://pasteboard.co/HoY6SfB.png

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions