【问题标题】:Error making POST request to an API with Angular 2使用 Angular 2 向 API 发出 POST 请求时出错
【发布时间】:2017-10-11 00:13:26
【问题描述】:

我正在尝试在我的 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

服务.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])
    });
  }

}

【问题讨论】:

    标签: api angular cors


    【解决方案1】:

    我相信传递给http.post 方法的第三个参数是RequestOptions object

       const headers= new Headers ({'Content-type':'application/json'});
       const options = new RequestOptions({ headers });
       this.http.post('https://website/api/v1/auth', user, options)
    

    此外,您不需要在发送对象之前对其进行字符串化,只需将用户对象作为正文发送

    您还应该检查以确保服务器在标头中返回 Access-Control-Allow-Origin

    【讨论】:

    • signIn(user:User){ const headers= new Headers ({'Content-type':'application/json'}); const options = new RequestOptions({ headers }); return this.http.post('website/api/v1/auth/sign_in', user,options) .map((response:Response)=>response.json()) .catch((error: Response)=>Observable.throw(error.json ())); }
    • 您还应该检查以确保服务器正在返回标头中的 Access-Control-Allow-Origin
    • 其实你也可以尝试使用 'text/plain' 而只是使用字符串来查看是否有效
    • 我在浏览器中启用了 CORS 插件,因此没有它也可以工作。我检查了一个获取请求。当我使用 text/plain 时,它给了我 401 未经授权。当我在邮递员中使用 text/plain 时也是如此。 (使用应用程序 json 它可以在邮递员中使用相同的数据).hmm 有趣
    • 你试过application/x-www-form-urlencoded; charset=UTF-8 并序列化对象
    猜你喜欢
    • 2014-12-04
    • 2021-11-12
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多