使用Angular 2向API发出POST请求时出错

时间:2017-05-11 20:16:02

标签: api angular cors

我正在尝试在Angular 2应用程序中发布帖子请求。我收到了一个错误。我有一个CORS插件启用,当我使用Postman时,请求成功,所以不知道什么可能是错的。我将不胜感激任何帮助:)

Failed to load resource: the server responded with a status of 404 (Not Found)
16:1 XMLHttpRequest cannot load https://website/api/v1/auth/sign_in. Response for preflight has invalid HTTP status code 404

Service.ts

import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import {User} from "./auth.model";

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

    signUp(user:User){
        const body= JSON.stringify(user);
        const headers= new Headers ({'Content-type':'application/json'});
        return this.http.post('https://website/api/v1/auth', body,{headers:headers})
            .map((response:Response)=> response.json())
            .catch((error: Response)=>Observable.throw(error.json()));
    }

    signIn(user:User){
        const body= JSON.stringify(user);
        const headers= new Headers ({'Content-type':'application/json'});
        return this.http.post('https://website/api/v1/auth/sign_in', body,{headers:headers})
            .map((response:Response)=>response.json())
            .catch((error: Response)=>Observable.throw(error.json()));
    }


}

signin.ts

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl, Validators,FormsModule} from '@angular/forms';
import {AuthService} from './auth.service';
import {User} from "./auth.model";

@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.css']
})
export class SigninComponent implements OnInit {
  myForm: FormGroup;

  constructor(private authService: AuthService) { }


  onSubmit(){
    const user= new User(this.myForm.value.email, this.myForm.value.password);
    this.authService.signIn(user).subscribe();
    console.log("c");
  }

  ngOnInit() {
    this.myForm= new FormGroup({
      email: new FormControl(null, [Validators.required,
        Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
      ]),
      password: new FormControl(null, [Validators.required])
    });
  }

}

0 个答案:

没有答案