1

Angular 2 http post not setting content type

Im trying to set headers on http.post with no luck.

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { User } from '../_models/index';

@Injectable()
export class UserService {
constructor(private http: Http) { }

create(username: string, firstname: string, lastname: string, email: string, password: string) {
    let headers = new Headers({
        'Accept' : 'application/json',
        'Content-Type': 'application/json'
    });
    let options = new RequestOptions({ headers: headers, method: 'post' });

    return this.http.post(
        'http://127.0.0.1:8080/api/users/register',
        JSON.stringify({username, firstname, lastname, email, password}),
        options
        // this.jwt()
    ).map(
        (response: Response) => response.json()
    );
}

I've set headers on my apache config

    <Directory /var/www/stockwatch_api>
            Header set Access-Control-Allow-Origin "*"
            Header set Access-Control-Allow-Headers "Content-Type"
            Header set Access-Control-Allow-Methods "POST, PUT, DELETE, GET, HEAD"

I've also set the same headers in my cakephp api app.

I'm getting this response:

Status Code: 501 Not Implemented

enter image description here

Community
  • 1
  • 1
user5569354
  • 55
  • 1
  • 9
  • 2
    The problem is with the backend. It is refusing the [CORS pre-flight OPTIONS request](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests). Try adding OPTIONS to list of allowed methods. – georgeawg Sep 02 '17 at 19:30
  • Thanks I tried that, didn't work. – user5569354 Sep 02 '17 at 21:07
  • Possible duplicate of [enable cors in .htaccess](https://stackoverflow.com/questions/14467673/enable-cors-in-htaccess) – georgeawg Sep 02 '17 at 22:15

1 Answers1

0

Try using headers.append()

let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
Aravind
  • 40,391
  • 16
  • 91
  • 110