JavaScript Web服务器接收请求请求
我正在尝试从Angular应用程序中的服务中获取请求,但是由于未定义,我无法从请求的正文中获取数据。这是我的代码。
Angular
setSessionName(sessionId: number, newSessionName: string): Observable<Session> {
const body = {
sessionId: sessionId,
newName: newSessionName
};
return this.httpClient.put<Session>(`${this.baseUrl}/set-session-name`, body);
}
}
服务器
const express = require('express');
const cors = require('cors');
const serverPort = 8080;
const app = express();
app.use(cors({
origin: ['http://localhost:4200']
}));
app.put('/set-session-name', (httpRequest, httpResponse) => {
console.log(httpRequest.body); // Output: undefined
httpResponse.sendStatus(200);
});
app.listen(serverPort, () => {
console.log(`Server running at http://127.0.0.1:${serverPort}`);
})
I'm trying to get PUT requests from a service in my Angular app, but I can't get the data from the request's body because is undefined. Here is my code.
ANGULAR
setSessionName(sessionId: number, newSessionName: string): Observable<Session> {
const body = {
sessionId: sessionId,
newName: newSessionName
};
return this.httpClient.put<Session>(`${this.baseUrl}/set-session-name`, body);
}
}
SERVER
const express = require('express');
const cors = require('cors');
const serverPort = 8080;
const app = express();
app.use(cors({
origin: ['http://localhost:4200']
}));
app.put('/set-session-name', (httpRequest, httpResponse) => {
console.log(httpRequest.body); // Output: undefined
httpResponse.sendStatus(200);
});
app.listen(serverPort, () => {
console.log(`Server running at http://127.0.0.1:${serverPort}`);
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要添加
app.use(express.json());
才能在节点服务器中添加支持JSON编码的身体you need to add
app.use(express.json());
in order to add support json encoded bodies in your node-server