【问题标题】:Node Express - Cannot POST / errorNode Express - 无法 POST / 错误
【发布时间】:2022-02-05 08:06:20
【问题描述】:

我一直在学习有关如何构建全栈 MEAN 应用程序的教程,并且到目前为止一切都运行良好(注册、登录和身份验证。)

我现在正在尝试对博客页面进行发布请求,但收到以下错误:

<pre>Cannot POST /blogs/newBlog</pre>

到目前为止,我所做的只是创建了一个模式、一个路由,然后对 index.js 进行了相关的更改。下面提供的架构文件是本教程作者在他的存储库中提供的(与其他两个文件不同的是,它是完整的形式。)问题仍然存在,所以我认为这不是问题。

博客架构:

/* ===================
   Import Node Modules
=================== */
const mongoose = require('mongoose'); // Node Tool for MongoDB
mongoose.Promise = global.Promise; // Configure Mongoose Promises
const Schema = mongoose.Schema; // Import Schema from Mongoose

// Validate Function to check blog title length
let titleLengthChecker = (title) => {
  // Check if blog title exists
  if (!title) {
    return false; // Return error
  } else {
    // Check the length of title
    if (title.length < 5 || title.length > 50) {
      return false; // Return error if not within proper length
    } else {
      return true; // Return as valid title
    }
  }
};

// Validate Function to check if valid title format
let alphaNumericTitleChecker = (title) => {
  // Check if title exists
  if (!title) {
    return false; // Return error
  } else {
    // Regular expression to test for a valid title
    const regExp = new RegExp(/^[a-zA-Z0-9 ]+$/);
    return regExp.test(title); // Return regular expression test results (true or false)
  }
};

// Array of Title Validators
const titleValidators = [
  // First Title Validator
  {
    validator: titleLengthChecker,
    message: 'Title must be more than 5 characters but no more than 50'
  },
  // Second Title Validator
  {
    validator: alphaNumericTitleChecker,
    message: 'Title must be alphanumeric'
  }
];

// Validate Function to check body length
let bodyLengthChecker = (body) => {
  // Check if body exists
  if (!body) {
    return false; // Return error
  } else {
    // Check length of body
    if (body.length < 5 || body.length > 500) {
      return false; // Return error if does not meet length requirement
    } else {
      return true; // Return as valid body
    }
  }
};

// Array of Body validators
const bodyValidators = [
  // First Body validator
  {
    validator: bodyLengthChecker,
    message: 'Body must be more than 5 characters but no more than 500.'
  }
];

// Validate Function to check comment length
let commentLengthChecker = (comment) => {
  // Check if comment exists
  if (!comment[0]) {
    return false; // Return error
  } else {
    // Check comment length
    if (comment[0].length < 1 || comment[0].length > 200) {
      return false; // Return error if comment length requirement is not met
    } else {
      return true; // Return comment as valid
    }
  }
};

// Array of Comment validators
const commentValidators = [
  // First comment validator
  {
    validator: commentLengthChecker,
    message: 'Comments may not exceed 200 characters.'
  }
];

// Blog Model Definition
const blogSchema = new Schema({
  title: { type: String, required: true, validate: titleValidators },
  body: { type: String, required: true, validate: bodyValidators },
  createdBy: { type: String },
  createdAt: { type: Date, default: Date.now() },
  likes: { type: Number, default: 0 },
  likedBy: { type: Array },
  dislikes: { type: Number, default: 0 },
  dislikedBy: { type: Array },
  comments: [{
    comment: { type: String, validate: commentValidators },
    commentator: { type: String }
  }]
});

// Export Module/Schema
module.exports = mongoose.model('Blog', blogSchema);

routes/blogs.js

const User = require('../models/user'); // Import User Model Schema
const jwt = require('jsonwebtoken');
const config = require('../config/database');

module.exports = (router) => {

  router.post('/newBlog', (req, res) => { // TODO: change URL
    res.send('test worked');
  });

  return router; // Return router object to main index.js
}

index.js

/* ===================
   Import Node Modules
=================== */
const env = require('./env');
const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const config = require('./config/database');
const path = require('path');
const authentication = require('./routes/authentication')(router);
const blogs = require('./routes/blogs')(router);
const bodyParser = require('body-parser');
const cors = require('cors'); 

const port = process.env.PORT || 8080;

// Database Connection
mongoose.connect(config.uri, {
  useMongoClient: true,
}, (err) => {
  // Check if database was able to connect
  if (err) {
    console.log('Could NOT connect to database: ', err);
 message
  } else {
    console.log('Connected to ' + config.db);
  }
});

// Middleware
app.use(cors({ origin: 'http://localhost:4200' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.use('/authentication', authentication);
app.use('/blogs', blogs);

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname + '/public/index.html'));
});

// Start Server: Listen on port 8080
app.listen(port, () => {
  console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode');
});

我一直非常喜欢这门课程,并希望得到任何帮助(即使只是为了排除可能的原因。)

完全错误:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /blogs/newBlog</pre>
</body>
</html>

【问题讨论】:

  • 你能粘贴完整的错误日志吗?
  • 您的文件中没有任何 .post 方法中间件
  • 我认为这行router.get('/newBlog',... 应该是帖子-> router.post('/newBlog' 因为它是使用app.use('/blogs', blogs); 安装的,所以url 将是/blogs/newblog
  • 道歉摩尔达。我现在更正了那条线。我将其更改为 GET 以查看发生了什么。当我将请求从 POST 更改为 GET 时,我得到了以下信息:.../Documents/MEAN-Stack-Blog/client/src/index.html 我还在原始帖子中添加了完整的错误消息。
  • Artur,我在中间件中添加了:app.use('/blogs', blogs)。我已将完整的错误消息添加到原始帖子的底部。

标签: node.js express


【解决方案1】:

您的问题与:

app.use('/blogs', blogs);

blogs 函数应该是采用 (req, res) 的函数,但它实际上采用 (router)

你有两个选择:

创建一个router 并传入blogs,例如app.use('/blogs', blogs(router));

添加app.post(),例如

app.post('/blogs/newBlog', (req, res) => {
  res.send('test worked');
});

【讨论】:

  • 我现在尝试按照您的建议将(router) 添加到app.use('/blogs', blogs)(在导入部分中删除和保留(router)。我还尝试将app.use('/blogs'); 中间件功能替换为一个您好心提供。仍然没有成功。完成应用程序的 index.js 文件可以在作者的存储库中找到:link
【解决方案2】:

试着从bodyparser改成表达手段……

而不是

app.use(bodyParser.json())

使用app.use(express.json())

【讨论】:

  • 不,不要再这样做了。自快递4
【解决方案3】:

请替换:


router.post('/newBlog', (req, res) => {
  res.send('test worked');
});

有了这个(在你所有的方法上“获取、发布、使用”等):

// Make sure to always add a slash both before and after the endpoint!
router.post('/newBlog/', (req, res) => {
  res.send('test worked');
});

如果我没有正确添加端点斜线,我会遇到这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2021-10-24
    • 1970-01-01
    • 2020-10-07
    • 2020-04-17
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多