Hello everyone I'm trying to connect mongo and node. But i'm getting cannot GET Please help me with this My code is as follows. It would be great if someone helps me in resolving this issue app.js
var express = require("express");
var bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/NammaDB');
var db = mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback) {
console.log("connection succeeded");
})
var app = express()
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('login', function(req, res) {
var name = req.body.username;
var pass = req.body.password;
var data = {
"eid": hello,
"pwd": hello,
}
db.collection('users').insertOne(data, function(err, collection) {
if (err) throw err;
console.log("Record inserted Successfully");
});
return res.redirect('/login.html');
})
app.get('/', function(req, res) {
res.set({
'Access-control-Allow-Origin': '*'
});
return res.redirect('login.html');
}).listen(3000)
console.log("server listening at port 3000");
My index.js code is as follows index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('It works!');
});
module.exports = router;
As it says in the expressjs 4.0 docs:
res.redirect([status,] path)
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code. If not specified, status defaults to “302 “Found”.
That means that res.redirect();
does not serve files; instead, it redirects/forwards the request to the specified path. So, you have to define an express get route for /login
, like this:
app.get("/login", (req, res) => {
//whatever you need to do
});
Here is the documentation
Here you just need to import routes and define middleware in your root
file
Give your path of index.js file
here I assume you have index.js
file inside routes/index.js
const routes = require('./routes/index')
and use middleware like
app.use('/get', routes);
Now your URL
looks like http://localhost:3000/get
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.