Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - Linking HTML form action to node js function

I'm trying to execute a function in node.js when a users enters information on a form in html. I keep getting 404 not found and am not sure where to go. I'm sure there are other questions similar to this but have searched around and can't find anything.

HTML Code:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>

<link rel = "stylesheet"
      type = "text/css"
      href = "style.css" />

<form action="/zipCheck" method="post" accept-charset="utf-8">
    <input placeholder="Enter your zip code to start" class = "zipInput">
</form>

</html>

Node.js code:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

console.log("hello");

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('short'));

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.post('/zipCheck', function(req, res){
    console.log("GOOD");
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The order of middleware loading is important: middleware functions that are loaded first are also executed first.

You added the /zipCheck route after the error handler, your requests will never reach this handler and your app will not print GOOD.

You need to reorder your routes handler, also add a slash before zipCheck

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.post('/zipCheck', function(req, res){
    console.log("GOOD");
});

// error handler
app.use(function(err, req, res, next) {
    
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...