简体   繁体   中英

Node.js failed to post request

I prepared a testing programme using node.js, and submit request in the browser. The server can be started successfully and connect to the database successfully. However, the browser returns "Cannot POST " and 404 not found when I input some values in the form and post it to localhost:3000/api/signup. Could anyone tell me which part in my code went wrong? Thanks!

 //server.js var express = require('express'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var config = require('./config'); var mongoose = require('mongoose'); mongoose.connect(config.database, function(err){ if(err){ console.log(err); }else{ console.log('Connected to the database'); } }); var app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(morgan('dev')); var api = require('./app/routes/api')(app, express); api.use('/api', api); app.get('*', function(req,res){ res.sendFile(__dirname + '/public/views/index.html'); }); app.listen(config.port, function(err){ if(err){ console.log(err); }else{ console.log("Listening on port 3000"); } }); 

 //user.js var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var Schema = mongoose.Schema; var UserSchema = new Schema({ name: String, username: {type: String, required: false, index: {unique: true}}, password: {type: String, required: true, select: false} }); UserSchema.pre('save', function(next){ var user = this; if(!user.isModified('password')){ return next(); } bcrypt.hash(user.password, null, null, function(err, hash){ if(err){ return next(err); } user.password = hash; next(); }); }); UserSchema.methods.comparePassword = function(password){ var user = this; return bcrypt.compareSync(password,user.password); } module.exports = mongoose.model('User', UserSchema); 

You don't have any POST handlers. This line here...

app.get('*', function(req,res){

...handles GET requests only. You can either change that to app.all(..) (which I'd only recommend during testing), or create an app.post(...) handler.

Please see the documentation here for more details on how to create handlers for various HTTP verbs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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