node.js - Node.js - Postman 中的 HTTP POST 请求问题
问题描述
我从 YouTube 视频中复制了这段代码,该视频介绍了如何使用 Node.js 制作一个 rest API。GET
请求和其他东西工作得很好,直到我尝试了一个请求POST
然后我遇到了一个错误:
Could not get any response
There was an error connecting to http://localhost:3000/posts.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General
我检查了控制台,这就是它所显示的
POST http://localhost:3000/posts
Error: socket hang up
Warning: This request did not get sent completely and might not have all the required system headers
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.24.0
Accept: */*
Cache-Control: no-cache
Postman-Token: ee8e3956-6963-45a5-8c7e-3bd41628b210
Host: localhost:3000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Request Body
视频中的人为他工作得很好,所以我想这可能与新更新有关,因为视频有点旧。我的 Postman 版本是 7.21.2
如果有人可以帮助解决此问题,我将不胜感激,因为我在网上查找了各种答案,但找不到特定于我自己的答案
下面是我设置端口和路由器的app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
app.use(bodyParser.json());
// Import Routes
const postsRoute = require("./routes/posts");
//Middlewares
app.use("/posts", postsRoute);
//Routes
app.get("/", (req, res) => {
res.send("we are on home");
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECT,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log("connected to DB!")
);
app.listen(3000);
这是 post.js 路由的代码
const express = require("express");
const router = express.Router();
const Post = require("../models/Post");
router.get("/", (req, res) => {
res.send("we are on posts");
});
router.post("/", async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description,
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
解决方案
推荐阅读
- python - 执行以下程序时出现类型错误
- linux - 如何获取 linux 中物理内存的详细使用情况?
- kubernetes - 具有 sessionAffinity 的 OpenShift 服务将流量转发到两个 pod
- mysql - MySQL - MOD() 返回 1 而不是 0
- python - 如何显示或保存调整大小的图像?
- google-apps-script - 启动 Google Web App 后如何加载 JavaScript 文件
- go - 带有“--skip-model”标志的“生成资源”命令导致资源错误
- angular - 为什么我需要标记检查?有角度的
- javascript - 如果选中,带有底部边框的导航栏会向上移动文本
- php - 上传大文件时 ini_set() 函数的 symfony 问题