【问题标题】:HTTP POST request to express server from angular front end从角度前端表达服务器的 HTTP POST 请求
【发布时间】:2019-04-26 17:31:06
【问题描述】:

我无法向在同一主机上运行的 api 发出 POST 请求,但在角度前端的另一个端口上运行 代码如下:

import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-addbook',
  templateUrl: './addbook.component.html',
  styleUrls: ['./addbook.component.scss']
})
export class AddbookComponent implements OnInit {
  addForm: FormGroup;
  constructor(private formBuilder: FormBuilder, private http:HttpClient) {
  }
  ngOnInit() {
    this.addForm=this.formBuilder.group({
      title: ['', Validators.required],
      description:['', Validators.required],
      genre: ['', Validators.required],
      author: ['', Validators.required],
      publisher: ['', Validators.required],
      pages: ['', Validators.required],
      image_url: ['', Validators.required],
      buy_url: ['', Validators.required]
    });
  }
  onSubmit(){
    if(this.addForm.valid){
      console.log(this.addForm.value);
      const data = this.addForm.value;
      const headers=new HttpHeaders({'Content-Type':'application/json'});
      this.http.post("http://localhost:3000/api/books",headers,data).subscribe(
        res=>{
          console.log(res);
        },
        err=>{
          console.log('err:'+err);
        }
      );
    }
  }
}

结果: 输出控制台:

输出网络:

如果您在第二张图片中看到标题已更改为 OPTIONS 而不是帖子

http://localhost:3000/api/books - 发布 api 和 http://localhost:4200 - 前端角度

我错过了什么??

【问题讨论】:

  • 有效载荷dataheaders 的顺序在您的情况下被翻转。查看我的答案以了解更多信息。
  • 您是否阅读了控制台中的消息?您需要阅读 CORS 并相应地更新您的后端(或添加代理,以更接近您的实际部署配置为准)。
  • 您似乎必须在您的 Express 服务器上启用 CORS。我添加了一个更新的答案。请检查是否有帮助。
  • @jonrsharpe,我会记住这一点。谢谢:)

标签: javascript node.js angular http mean-stack


【解决方案1】:

如果您查看HttpClient,它的post 方法的签名为:

post(
  url: string, 
  body: any, 
  options: { 
    headers?: HttpHeaders | { [header: string]: string | string[]; }; 
    observe?: HttpObserve; 
    params... = {}
): Observable<any>

所以这个:

this.http.post("http://localhost:3000/api/books", headers, data)...

应该是:

this.http.post("http://localhost:3000/api/books", data, { headers })...

Payload Data(body) 是 post 方法的第二个参数,然后是 options,其中包含 headers 之类的内容

另外:

查看您的控制台警告,您的 Express 服务器似乎由于 CORS 政策而阻止请求。

您还必须在 Express 服务器上启用 CORS。方法如下

安装 CORS:

npm install cors --save

然后在您的 Express 服务器中:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

注意:这只是一个示例实现,可能会根据您的实现而改变。

【讨论】:

  • SiddAjmera,我们的答案是正确的。我也投了反对票。添加了你的支持
  • 谢谢先生,您刚刚救了我的头免于骨折,直到现在我才投票,先生。感谢您的帮助
  • @freepowder,实际上我们错过了一个关键的事情。控制台错误提出了 CORS 策略问题。所以 CORS 必须在 OPs express 服务器上实现。这就是我们错过的,因此被否决了。我不明白为什么我的第二个答案被否决了。说明为什么有人投反对票是一种普遍的礼貌。
  • @SiddAjmera CORS 是 post 方法签名错误的另一个问题。正如我在其他评论中所说,您的回答是正确的(就像我的一样)。反对意见来自不提供任何技术解决方案的人,只是环顾四周试图表现得好像他们对此有所了解。
猜你喜欢
  • 2013-12-09
  • 2011-06-01
  • 2021-08-15
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多