【问题标题】:Error on post Express.js发布 Express.js 时出错
【发布时间】:2015-10-10 14:51:14
【问题描述】:

我对联系表有疑问。我只是想用快递做一个简单的帖子。

我有以下代码:

views/contacto.jade

  extends layout-inside
  block content
  .main-container
  form(action='contacto', name='contacto', id='contacto', method='post')
  section.cover.fullscreen.image-bg.overlay
  .background-image-holder
  img.background-image(alt='image', src='/images/bg-6.jpg')
  |                 
  .container.v-align-transform
  .row
  .col-sm-6.col-sm-offset-3
  .feature.bordered.text-center
  h4.uppercase Contacto
  |                                 
  form.text-left
  input(type='text', name='name', placeholder='Nombre')
  |                                     
  input(type='text', name='email', placeholder='Email')
  |                                     
  input(type='text', name="telefono", placeholder='Teléfono')
  |                                     
  textarea(name="mensaje",  placeholder='mensaje')
  |                                     
  input(type='submit', value='Enviar')
  |  

routes/index.js

  router.get('/contacto', function(req, res, next) {
  res.render('contacto', { title: 'Contacto'});
  });

当我以表格形式发帖时,我收到了这个错误:

  Error: Not Found
  at /Users/dev/node/website/app.js:33:13
  at Layer.handle [as handle_request] (/Users/dev/node/website/node_modules/express/lib/router/layer.js:95:5)
  at trim_prefix (/Users/dev/node/website/node_modules/express/lib/router/index.js:312:13)
  at /Users/dev/node/website/node_modules/express/lib/router/index.js:280:7
  at Function.process_params (/Users/dev/node/website/node_modules/express/lib/router/index.js:330:12)
  at next (/Users/dev/node/website/node_modules/express/lib/router/index.js:271:10)
  at /Users/dev/node/website/node_modules/express/lib/router/index.js:618:15
  at next (/Users/dev/node/website/node_modules/express/lib/router/index.js:256:14)
  at Function.handle (/Users/dev/node/website/node_modules/express/lib/router/index.js:176:3)
  at router (/Users/dev/node/website/node_modules/express/lib/router/index.js:46:12)

你知道为什么会这样吗?文件似乎不存在。

谢谢

【问题讨论】:

  • router.get 是一个 GET 请求,如果它是一个你正在监听的 POST 请求,它应该是 router.post,甚至是 router.all 对于所有类型?

标签: javascript node.js express


【解决方案1】:

它们是不同的 HTTP 动词,GETPOST 不同,在执行 GET /contactos 时,您会返回一个视图,没关系。单击提交时,您将尝试执行POST request

您可以添加类似这样的内容来处理通过 POST 提交的表单:

 router.post('/contacto', function(req, res, next) {
  var formData = request.body;
  // Do stuff
  return response.end(201);
 });

对于您的 API,您应该在路由前加上 /api,例如:/api/contacts。另外,你应该用英文编码。

编辑。 Express 4 配置

您应该使用Router 对象来设置您的路线,如this other post 中所述。

【讨论】:

  • 谢谢!这份工作对我来说很完美。我在 app.post 而不是 router.post 中写帖子你知道区别吗? :)
  • 当您将 Express 的路由器配置为 Express 4 设置时,您必须以某种方式执行 router.post。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2013-12-24
  • 2018-12-03
相关资源
最近更新 更多