简体   繁体   中英

HTTP POST request to express server from angular front end

I couldn't do the POST request to the api running in the same host but on another port from angular front end Here's the code:

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

Result: Output Console:

输出控制台

Output Network:

输出网络

if you see in the second picture the header was changed to OPTIONS instead of post

http://localhost:3000/api/books - post api and http://localhost:4200 - front-end angular

what am i missing??

If you have a look at HttpClient , it's post method has a signature of:

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

So this:

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

should be:

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

Payload Data( body ) is the Second Argument to the post method and then comes options which contain things like headers

ALSO:

Looking into your console warnings looks like your Express Server is blocking requests due to the CORS Policy.

You'll also have to enable CORS on your express server. Here's how

Install CORS:

npm install cors --save

Then in your 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')
})

NOTE: This is just a sample implementation and might change according to your implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM