从角度前端向服务器表达HTTP POST请求

时间:2018-11-24 12:01:16

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

我无法向在同一主机上但从前端的另一个端口上运行的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);
        }
      );
    }
  }
}

结果: 输出控制台:

Output Console

输出网络:

Output Network

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

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

我想念什么?

1 个答案:

答案 0 :(得分:0)

如果您查看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 })...

有效载荷数据(body)是post方法的第二个参数,然后出现options,其中包含类似headers

的内容

还:

由于CORS政策,查看控制台警告似乎是Express Server阻止了请求。

您还必须在快递服务器上启用CORS。这是

安装CORS:

npm install cors --save

然后在您的Express Server中:

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')
})

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