【问题标题】:Cannot post using express不能使用快递发帖
【发布时间】:2021-02-24 03:20:19
【问题描述】:

(更新)感谢cmets中的许多人,我解决了这个问题,现在我遇到了一个新问题。保存数据后,我似乎无法重定向到主页。我被一个中间 HTML 卡住了,它向我显示了保存的 JSON 语句。

我一直在尝试使用 html 表单将信息发布到 API,但我总是收到错误 Cannot POST /。我已经尝试了很多我在 GitHub 上看到的 YouTube 教程和示例,但我似乎无法让它发挥作用。以下是我一直在使用的代码。有什么我做错或没看到的吗?

这是 server.js(虽然我不认为问题出在此处):

const express = require('express');
const mongoose = require('mongoose');
const app = express();
 
mongoose.connect(process.env.DATABASE_URL, {useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) =>  console.error(error))
db.once('open', () => console.log('connected to database'))
 
app.use(express.json())
const jugadorRouter = require('./routes/jugadores')
app.use('/jugadores', jugadorRouter)
 
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

这是表单所在的索引

<form name="form" method="post" action="/">
<div class="form-control">
  <label for="username">Usuario</label>
  <input type="text" name="username" id="username" placeholder="Ingrese su usuario..." required />
</div>
<div class="form-control">
  <label for="room">Equipo</label>
  <select name="room" id="room">
    <option value="rojo">Equipo rojo</option>
    <option value="amarillo">Equipo Amarillo</option>
    <option value="blanco">Equipo Blanco</option>
  </select>
</div>
<button id="login" type="submit" class="btn" onclick="javascript: form.action='Gerente.html'" formmethod="post">Gerente</button>                
</form>

这是 jugadores.js post 方法所在的位置:

const express = require('express')
const router = express.Router()
const Jugador = require('../model/jugador')
 
router.post('/', async (req, res) => {
 console.log(req.body);
 const jugador = new Jugador({
  username: req.body.username,
  room: req.body.room
})
try{
  const newJugador = await jugador.save()
  res.status(201).json(newJugador)
}catch(err){
  res.status(400).json({message: err.message})
}
res.render('public/Gerente', {
  username: username,
  room: room
});
res.end();
});
 
module.exports = router

这是我的 jugador.js

const mongoose = require('mongoose')
//login schema
const jugadorSchema = new mongoose.Schema({
username:{
 type: String,
required: true
},
Date:{
type: Date,
required: true,
default: Date.now
}
})
 
module.exports = mongoose.model('Jugador', jugadorSchema);

【问题讨论】:

  • 您在浏览器中打开的网址是什么?
  • 我在 localhost:3000 上运行它,所以只要它运行 index.html 就会加载。
  • 原来是http://localhost:3000/?
  • 是的,没错

标签: javascript node.js forms express post


【解决方案1】:

当你的服务器设置好后,你的 POST 路由是/jugadores

所以表格应该是:

&lt;form name="form" method="post" action="/jugadores"&gt;

并且按钮不应该有onclickformmethod,比如:

&lt;button id="login" type="submit" class="btn"&gt;Gerente&lt;/button&gt;

另外,让服务器可以处理表单添加:

app.use(express.urlencoded({extended: true}))

【讨论】:

  • 我试过你说的,得到了​​这个:{"message":"Jugador 验证失败:用户名:Path username is required., room: Path room is required."}跨度>
  • 太棒了!所以现在您可以到达您的快速路线,但它只是设置为处理 json 正文(例如当您通过 javascript fetch 函数调用它时)。查看有关Handling forms in Express 的帖子。 app.use(express.urlencoded({extended: true})) 应该可以解决这个问题。
  • 直接用bodyparser最好吗
【解决方案2】:

原答案

1.您已指定在 server.js (app.use('/jugadores', jugadorRouter)) 中的每个 api 路由之前使用 /jugadores,因此在 Html 页面中,您的操作将如下所示

html

 <form name="form" method="post" action="/jugadores/">

如果您想使用此代码,您的 api 调用将如下所示 http://localhost:3000/jugadores/,更改将在您的 html 表单中完成

2.如果您只想在路由中使用/ 而不是从app.use('/jugadores', jugadorRouter) 中删除/jugadores,那么在Html 页面中,您的操作将如下所示

html

 <form name="form" method="post" action="/">

server.js

  app.use(jugadorRouter)

如果您想使用此代码,您的 api 调用将如下所示 http://localhost:3000/,更改将在您的 server.js 文件中完成

更新

正如您在评论中提到的那样,您遇到了错误

{"message":"Jugador 验证失败:用户名:路径用户名是必需的。房间:路径房间是必需的。"}

要在 Express 中接收 POST 值,您首先需要包含 body-parser 中间件,它会在您的路由处理程序中公开 req.body 上提交的表单值。如本文所述tutorial

先安装body-parser

server.js

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
    extended: true
}));

【讨论】:

  • 或者如果您想在/ 提供该路线,您可以将使用语句更改为app.use('/', jugadorRouter)
  • 不,如果他只想使用/,那么如果他使用app.use('/', jugadorRouter),那么他必须使用app.use(jugadorRouter),而不是请求url看起来像这样http://localhost:3000//
  • 我尝试了您的两个建议,但我现在收到此消息:{"message":"Jugador 验证失败:用户名:路径username 是必需的。房间:路径room 是必需的。 "}
  • 这意味着您的 api 正在使用该路由,但 api 没有从您在模型中指定 required: true 的 html 表单中获取任何数据,因此它会抛出这样的错误,这意味着您的html 表单,因为它没有在请求中向 api 发送数据
  • @andres 现在应用我在答案中更新的更改,它将起作用
【解决方案3】:

1.错误是什么意思?

  • 在创建快速服务器时,您注册了一个路由处理程序列表。错误Cannot POST /表示express找不到路由的POST注册/

2。目前情况如何?

  • 完成后,表单提交发送POST请求到路由/
  • express 搜索其路由注册列表。它找不到POST / 请求的路由句柄。所以它大喊错误

3.如何解决?

  • 当你声明像app.use('/jugadores', jugadorRouter)这样的路由器处理程序时,路由器处理程序的路径将以/jugadores为前缀。因此,jugadores.js 中的POST / 实际上会变成POST /jugadores
  • express 目前唯一的路由句柄是POST /jugadores。似乎应该在这里处理表单提交。因此,您可以像这样更改 html 表单操作值

&lt;form name="form" method="post" action="/jugadores"&gt;

感谢阅读!

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2021-11-06
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多