简体   繁体   English

Node Express - 无法 POST / 错误

[英]Node Express - Cannot POST / error

I have been following a tutorial on how to build a full stack MEAN application and everything has been functioning fine up until this point (registration, login and authentication.)我一直在关注如何构建一个完整的堆栈 MEAN 应用程序的教程,到目前为止一切都运行良好(注册、登录和身份验证。)

I'm now trying to do a post request for the blog page and am receiving the following error:我现在正在尝试对博客页面进行发布请求,但收到以下错误:

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

All that I've done so far is create a schema, a route and then made the relevant changes to index.js.到目前为止,我所做的只是创建一个模式、一个路由,然后对 index.js 进行相关更改。 The schema file provided below is the one provided by the author of the tutorial in his respository (unlike the other two files it is in it's completed form.) The problem still persists and so I do not believe it to be the problem.下面提供的架构文件是本教程作者在他的存储库中提供的(与其他两个文件不同的是,它是完整的形式。)问题仍然存在,所以我不认为这是问题所在。

Blog schema:博客架构:

/* ===================
   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路线/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 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');
});

I have been enjoying this course greatly and would appreciate any help (even if it is to simply rule out possible causes.)我一直非常喜欢这门课程,并希望得到任何帮助(即使只是为了排除可能的原因。)

Error in full:完全错误:

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

Your problem has to do with:您的问题与以下有关:

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

The blogs function should be a function taking (req, res) but it actually takes (router) . blogs函数应该是一个采用(req, res)的函数,但它实际上采用(router)

You have two options:你有两个选择:

Create a router and pass into blogs , eg app.use('/blogs', blogs(router));创建一个router并传入blogs ,例如app.use('/blogs', blogs(router)); or或者

Add app.post() , eg添加app.post() ,例如

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

Check spelling of your route检查路线的拼写

In my case I was posting from a url that had a missing letter.就我而言,我是从一个缺少字母的网址发帖的。

I was doing POST /webooks/ but I needed to do POST /webhooks (note the missing h letter).我正在做POST /webooks/但我需要做POST /webhooks (注意缺少的h字母)。

So it may also be that you misspell your routes.所以也可能是你拼错了你的路线。

Just try to change from bodyparser to express means...只是尝试从bodyparser更改为表达手段......

instead of代替

app.use(bodyParser.json())

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

Please replace this:请替换这个:


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

With this (on all your methods "get, post, use" etc):有了这个(在你所有的方法上“获取、发布、使用”等):

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

I encounter this issue mostly if I don't add endpoint slashes properly.如果我没有正确添加端点斜线,我会遇到这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM