简体   繁体   English

无法使用快递发布/出错

[英]Cannot POST / error using express

I am trying to create a simple form handler using express.我正在尝试使用 express 创建一个简单的表单处理程序。 I tried the code below for my form:我为我的表单尝试了以下代码:

<form class="form"  action="/" method="post" name="regForm">              
    <div class="form-group">
        <input type="text" name="username" class="form-control" id="username" placeholder="Username">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

And here is my app.js code:这是我的 app.js 代码:

const port = 3000;

var express = require('express'),
    app = express(),
    server = require('http').createServer(app);
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

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

app.use(bodyParser.json());

app.post('/',function(req,res){
   var username = req.body.username;
   var html = 'Hello:' + username;
   res.send(html);
   console.log(html);
});

server.listen(port);

I keep getting the error "CANNOT POST /" after submitting the form.提交表单后,我不断收到错误“CANNOT POST /”。 Am I missing something like a module?我错过了像模块这样的东西吗?

This way you should try这种方式你应该尝试

const port = 3000;

var express = require('express'),
    app = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

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

app.use(bodyParser.json());

app.get('/', function(req, res){
  res.render('form');// if jade
  // You should use one of line depending on type of frontend you are with
  res.sendFile(__dirname + '/form.html'); //if html file is root directory
 res.sendFile("index.html"); //if html file is within public directory
});

app.post('/',function(req,res){
   var username = req.body.username;
   var htmlData = 'Hello:' + username;
   res.send(htmlData);
   console.log(htmlData);
});

app.listen(port);

Things you should keep in mind for future Ref :您应该记住的事项以供将来参考:

  1. You were extending url encode to true您正在将 url 编码扩展到 true
  2. You were not having any get request for your form您没有任何获取表单的请求
  3. You were using HTML named variable which is one of bad practices您使用的是 HTML 命名变量,这是一种不好的做法

In my case, I wasn't paying attention to the url I was posting from.就我而言,我没有注意我发布的网址。

I had the page login http://localhost:5000/login which was posting and, if successful, renders the page account http://localhost:5000/account .我有页面登录http://localhost:5000/login正在发布,如果成功,则呈现页面帐户http://localhost:5000/account

But, playing few times with these 2 pages, the link remained at http://localhost:5000/account but displayed the login page.但是,在这两个页面上玩了几次,链接仍然在http://localhost:5000/account但显示登录页面。 So, when I was clicking the log in button which had a form with method = "post" , I was getting the error Cannot POST /account .因此,当我单击具有method = "post" form的登录按钮时,我收到错误Cannot POST /account

So the fix was to correctly render the login page, by typing in the url of login page http://localhost:5000/login .所以修复是通过输入登录页面http://localhost:5000/login的 url 来正确呈现登录页面。

Another Way is that we can use .route method provided by express另一种方式是我们可以使用 express 提供的 .route 方法

https://expressjs.com/en/guide/routing.html https://expressjs.com/en/guide/routing.html

Eg:例如:

app.route("url")
   .get(function())

   .post(function());

remember to close the .route function using semi colon ;记得用分号关闭 .route 函数;

Seems to work fine here.似乎在这里工作正常。

The only bug I found is here:我发现的唯一错误在这里:

extended: true;

You need to remove the semicolon at the end.您需要删除最后的分号。

Also, you don't need action="/" in your form tag, just FYI.此外,您的表单标签中不需要 action="/" ,仅供参考。

You should call router instead of app
const router = express.Router();

router.use(bodyParser.urlencoded({ extended: false }));

router.post('/',function(req,res){
   var username = req.body.username;
   var htmlData = 'Hello:' + username;
   res.send(htmlData);
   console.log(htmlData);
});

Check for any trailing whitespace in your path strings.检查路径字符串中的任何尾随空格。 Sounds super simple but it took me two days to figure this was even possible.听起来超级简单,但我花了两天时间才发现这甚至是可能的。 It seems that if your paths look like this如果你的路径看起来像这样

router.post('/foo ', (req, res)=> { // I hope you see it!
    res
        .status(200)
        .send({msg: 'Foo!'})
})

Instead of this而不是这个

router.post('/foo', (req, res)=> {
    res
        .status(200)
        .send({msg: 'Foo!'})
})

You will get the "Cannot METHOD /PATH" error.您将收到“Cannot METHOD /PATH”错误。 It just so happens the browser is nice enough to truncate the trailing whitespace in it's error message as to not inconvinience you with unecessary information.碰巧浏览器足够好,可以截断错误消息中的尾随空格,以免不必要的信息给您带来不便。

Stay safe kids, use "highlight whitespaces" in your editors for your own sanity.保持安全的孩子,在您的编辑器中使用“突出显示空白”以保持您自己的理智。

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

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