app.module.ts文件内引入httpClient模块
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
],
})
***.component.ts内引入httpClient
import { HttpClient } from '@angular/common/http';
export class ***Component implements OnInit {
url: string = 'http://11.111.111.11:3000/';
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get(this.url).subscribe(data => {
let result = JSON.parse(JSON.stringify(data));
}
};
}
服务端node.js应用:
router.get("/", function (req, res, next) {
res.json({
user: 'tobi'
})
});
☆笔记
前端get请求数据组装
参数数据可以设置请求头header,也可不用设置header。
Import { HttpClient, HttpHeaders, HttpParams } from ‘@angular/common/http';
ngOnInit(): void {
let params = new HttpParams().set('str', '123456').set('ta', 'test');
this.http.get(this.url, {params}).subscribe(data => {})
let httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
params: { username:'test', age:'24' },
}
this.http.get(this.url, httpOptions).subscribe(data => {})
}
node.js服务端解析get请求
const url = require('url');
router.get("/", function (req, res, next) {
let params = url.parse(req.url,true).query;
console.log('--params--',params, params.str, params.ta);
res.json({ })
});
post请求
post请求更加安全规范。 前端post请求数据object
this.http.post(this.url, {
test: ''
}).subscribe(data => {});
Node服务器端接收post数据也更加清晰明了
router.post("/", (req, res) => {
console.log('--post--',req.body);
})
node.js响应请求常见返回形式
在http请求通信中,200表示一切正常。
响应get/post请求,可以发送带状态码的数据体,无状态码前端页面也不会报错
res.send({
code: 200,
data: {
context: ''
}
});
也可以直接返回json形式
res.json({
data: ''
});
|