That is your server:
const express = require('express')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}) );
app.all("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.post('/ping', function (req, res) {
res.send(req.body)
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
That is your angular client:
import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = { id : 1, name : 'Hello'};
constructor(private http: HttpClient) { }
callServer() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http.post('http://127.0.0.1:3000/ping', JSON.stringify(this.user), {
headers: headers
})
.subscribe(data => {
console.log(data);
});
}
}
repo https://github.com/kuncevic/angular-httpclient-examples
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…