要解决Angular 7的HttpClient post请求未发送到Node.js服务器的问题,你可以按照以下步骤进行操作:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
...
})
export class AppModule { }
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/api/endpoint', (req, res) => {
console.log(req.body); // 打印接收到的请求数据
res.send('请求已收到');
});
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
import { HttpClient, HttpHeaders } from '@angular/common/http';
constructor(private http: HttpClient) { }
sendPostRequest() {
const url = 'http://localhost:3000/api/endpoint'; // 替换为你的服务器端点URL
const headers = new HttpHeaders().set('Content-Type', 'application/json');
const data = { name: 'John Doe', age: 30 }; // 替换为你要发送的数据
this.http.post(url, data, { headers }).subscribe(
response => {
console.log(response); // 打印服务器响应
},
error => {
console.log(error); // 打印错误信息
}
);
}
通过按照以上步骤进行操作,你应该能够正确地发送POST请求到Node.js服务器并获得响应。如果仍然遇到问题,你可以检查浏览器的开发者工具中的网络请求日志和服务器端的日志以获得更多的信息。