服务端用的是 express
server.js
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.header("Access-Control-Allow-Origin", "*") // 允许跨域
console.log(req.query) // 请求数据
res.send('Hello World!') // 响应数据
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
测试过了 http://localhost:3000 启动正常
PS D:\WorkSpace\Transfer\Angular\HttpRequest\server> node server.js
Example app listening at http://localhost:3000
这是 angular 代码
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
private url = 'http://localhost:3000?bookName=Java';
getRequest(): Observable<string> {
alert('发送请求')
return this.http.get<string>(this.url)
}
constructor(private http: HttpClient) { }
ngOnInit(): void {
console.log(this.getRequest())
}
}
现在的问题是, 不管服务端是打开状态, 还是关闭状态, 都请求不到服务端
服务端也接收不到数据
也没有报错
下面是测试图
已解决, 写了一个DemoNote
Angular 向服务端发送 Http 请求
准备工作
app.component.html
server.js
最简单的 Http 请求
模块引入
app.module.ts -> @Append
simple.component.ts -> @Append
编写测试方法
simple.component.ts -> @Append
运行
启动 server.js
启动 angular
访问 http://localhost:4200 后
客户端控制台输出如下