那是你的服务器:
const express = require('express')const bodyParser = require('body-parser');const app = express()app.use(bodyParser.json());app.use(bodyParser.urlenpred({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!')})
那是您的有角度的客户:
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); }); }}
回购https://github.com/kuncevic/angular-httpclient-
examples
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)