来自服务器的日志记录响应不起作用

loging response from server does not work

我正在学习 Coding Garden 的教程。他在那里写入数据库并将其发送回客户端。

当我尝试这样做时,我没有得到服务器的响应。我想我的代码中出现了混淆。

当我转到 localhost/5000/posts 时,没有数据库。为什么我没有收到错误消息或数据库?

此致

预期结果https://youtu.be/JnEH9tYLxLk?t=3060

客户代码

const form = document.querySelector('form');
const loadingElement = document.querySelector(".loading");
const API_URL = "http://localhost:5000/posts";
      
      
loadingElement.style.display = "none";

form.addEventListener('submit', (event) => {
    event.preventDefault();
    const formData = new FormData(form);
    const name = formData.get('name');
    const content = formData.get('content');
    
    const post = {
        name,
        content
        
    };
    
    form.style.display = "none";
    loadingElement.style.display= "";
    
    fetch(API_URL, {
        method: "POST",
        body: JSON.stringify(post),
        headers: {
            "content-type": "application/json"
        }
    }).then(response => response.json())
    .then(createdPost => {
        console.log(createdPost);
        
    });
    
});

服务器代码

const express = require("express");
const cors = require('cors');
const monk = require("monk");

const app = express();

const db = monk("localhost/posts");
const posts = db.get("posts");


app.use(cors());
app.use(express.json());

app.get("/", (req, res) => {
       res.json({
           message: "Post"
       });
});

function isValidPost(post){
    return post.name && post.name.toString().trim() !== "" &&
        post.content && post.content.toString().trim() !=="";
}


app.post("/posts", (req, res) => {
    if (isValidPost(req.body)){
        const post = {
            name: req.body.name.toString(),
            content: req.body.content.toString(),
            created: new Date()
        };
        //console.log(post);
        posts
            .insert(post)
            .then(createdPost => {
                 res.json(createdPost);
                  });
                
    }else {
        res.status(422);
        res.json({
           message: "Hey, Titel und Inhalt werden benötigt!" 
        });
    }
});

app.listen(5000, () => {
  console.log('Listening on http://localhost:5000');
});

你忘了处理post.insert(...)失败被拒绝的情况。在这种情况下,您的服务器不会发送任何响应,请求将挂起。添加以下内容:

posts
      .insert(post)
      .then(createdPost => {
         res.json(createdPost);
      })
      .catch(err => {
         console.log(err);
          res.status(500).json({errorMessage: err.message});
      });

使用 catch 处理 fetch 方法。它可能会赶上。

fetch().then().catch(err => ...)