I have been struggling with this for a while now and can't find anything on the Internet about it, so I was wondering if somebody has any experience getting data in Ionic with Sequelize and the routing with Express.js.
This is wat I got:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('./routes/index');
var cars = require('./routes/cars') (app);
app.use('/cars', cars);
routes/cars.js
var models = require('../models');
var express = require('express');
var router = express.Router();
router.get('/cars', function(req, res) {
models.Car.findAll()
.then(function(data){
res.json(data);
})
.catch(function(error){
console.log("ops: " + error);
res.status(500).json({ error: 'error' });
});
});
module.exports = router;
models/cars.js
"use strict";
module.exports = function(sequelize, DataTypes) {
var Car = sequelize.define("Car", {
name: DataTypes.STRING,
favorite: DataTypes.INTEGER
}, {
freezeTableName: true,
tableName: 'car'
});
return Car;
};
I have tried multiple ways to get this to work, but when I go to http://localhost:8100/cars the browser outputs:
Cannot GET /cars
Can anyone please help me?
When you use express.Router(), you need to tell the app to use your router:
http://expressjs.com/4x/api.html#router
router = require('./routes/cars')
app.use('/', router);
You exposed the route '/cars' in app.js, and '/cars' as a subroute in cars.js resulting in '/cars/cars'
Related
**App.js Code**
const express = require("express");
const { default: mongoose } = require("mongoose");
const gaming = require("./routes/gaming");
const app = express();
app.use(express.json());
app.use("/", gaming);
const dbConnect = mongoose.connect("mongodb://localhost:27017/Gaming");
const mySchema = new mongoose.Schema({
name: String,
genre: String,
games: String,
})
const User = mongoose.model('gaming', mySchema);
app.listen(8000, ()=>{
console.log("listing at port 8000");
})
***Routes Folder Code***
const express = require("express");
let router = express.Router();
router.post("/gaming", (req,res)=>{
const addingData = new User({
name: req.body.name,
genre: req.body.genre,
games: req.body.games
})
addingData.save((err,result)=>{
if (err = true){
console.log(err);
}else{
console.log("Document dubmited successfully");
}
})
res.send("saved new data");
})
module.exports = router;
I don't know why its saying User is not defined because I exported router properly into the app.js by using module.exports = router. I think the module.export is not working properly and not bringing the code to app.js file. Thanks for the help
As the accepted answer is quite weird and not resolve the root cause. I write my 2 cents here.
Node separates code by modules by default, which mean your app's code and your gaming's route code won't interfere/know each other.
To make it work, you import or require other modules into the one you want to use.
In your case, you need to import User into the gaming route.
instead of
const User = mongoose.model('gaming', mySchema);
Try using
const User = (module.exports = mongoose.model('gaming', mySchema));;
I have a mongodb collection with a few examples and I was trying to display them on my get method but it keeps showcasing the Processing, Please wait... buffer screen without outputting any result. I am wondering why it takes so long and does not display even after an hour and more when it displayed quite quickly on my simpler tests before.
This is my Usermodel
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema(
{
username: { type:String,unique:true,required:true},
email:{type:String,unique:true,required: true},
password:{type: String,required:true,},
isAdmin:{type:Boolean,default: false,}, },
{
timestamps: true,
});
const userModel = mongoose.model("users_list",userSchema);
This is the user router
const express = require('express');
const userModel = require('../models/users');
const { model } = require('mongoose');
const router = require("express").Router();
router.get("/getUser",(req,res)=> {
userModel.find({},(err,result)=>{
if(err){
res.json("There is an error");
}
else{
res.json(result);
console.log("got result");
console.log(result);
}
});
res.send("Ok");
});
module.exports = router;
And here is how my index.js where all the routers are called and fixated.
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const userRouter = require('./apis/routers/userRouter');
const cors = require("cors");
dotenv.config();
mongoose
.connect(process.env.MONG_URL)
.then(() => console.log("DB Connection Successful!"))
.catch((err) => {
console.log(err);
});
app.use(cors);
app.use(express.json());
app.use('/api/users',userRouter);
I have given the right MongoDB URL and it is not enclosed in quotation marks or anything from .env
And right here as you can see in the image, the postman keeps doing this
This sending request is unending and doesn't fetch the data at all. How can I resolve this?
I'm a newbie in Nodejs and I'm coding a to-do app as a practical exercise. I'm having a problem that I cannot return to my index page "/" after using the DELETE method in Express. I use the deleteMany() of Mongoose to delete my docs, however after deleted all of those docs I couldn't return to the "/" page, the system threw an error in the console:
DELETE http://localhost:3000/ 404 (Not Found)
although using res.redirect("/") is fine with POST method. I've found a guy with the same problem as mine on Stack Overflow, but his solutions are not working in my app. Another solution of him is using pure Javascript to redirect from the client, however I want to do this job in the severside.
My files:
routes.js
module.exports = function(app) {
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
var db = require("./db");
app.get("/", function(req,res,next) {
db.task.find()
.then(tasks => {
res.render("index", {tasks: tasks})
});
})
}
controller.js
module.exports = function(app) {
const routes = require("./routes.js");
const apiRoutes = require("./api.js");
app.use(function(req,res,next) {
console.log(`GET ${req.url}`);
next();
})
app.use("/api", apiRoutes);
routes(app);
}
api.js
var express = require("express");
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
var db = require("./db");
router.post("/post", urlencodedParser, function(req,res) {
new db.task({"name": req.body.item, "status": "incompleted"})
.save(err => {
if (err) throw err;
console.log(req.body.item);
});
res.redirect("/");
}).delete("/delete/:item", function(req,res) {
var result = [];
var item = req.params.item;
//Config the url task to its original name
var delTask = item.replace(/\-/g," ").replace(/;/g,"-");
//Logging out the deleted task
db.task.find({"name": delTask}).then((foundTasks) => {
foundTasks.forEach(function(tasks){
var removedDoc = {"name": tasks.name, "Object_Id": tasks._id};
result.push(removedDoc);
})
})
db.task.deleteMany({"name": delTask}, (err) => {
if (err) throw err;
console.log("Removed items: ", result);
})
res.redirect("/");
})
module.exports = router;
You don't have to worry about the db.js file, because it just help me to create mongoose schema and completely do nothing with http or express. And finally the controller.js will be required in the app.js.
Trying to make a login app with nodejs express.
However after I run it. it shows TypeError: express.Router is not a function.
My express is the latest version4.13.4. Can anyone help me?Here is the code.
var User = require('../modules/user');
var config = require('../../config');
var secretKey = config.secretKey;
module.exports = function(app,express){
var api = express.Router;
api.post('/signup', function(req,res){
var user = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password
});
user.save(function(err){
if(err){
res.send(err);
return;
}
res.json({ message: 'user has been created'});
})
});
return api;
};
It should be var api = express.Router();
I can't see the require to include the express library.
var express = require('express');
var app = express();
Also remember to make
$ npm install express --save
To install it.
Here is the reference
http://expressjs.com/en/4x/api.html
http://expressjs.com/en/starter/installing.html
var api = express.Router();
or try this code :
var router = require('express').Router(),
User = require('../modules/user'),
config = require('../../config');
router
.post('/signup', function (req, res, next) {
var user = new User(req.body);
user.save(function (err) {
if (err) res.send(err);
else res.json({message: 'user has been created'});
})
});
module.exports = router;
You need to require the express module, before calling the Router method, with this you can add more HTTP method to "/signup" route.
var express = require('express');
var User = require('../modules/user');
var config = require('../../config');
var api = express.Router();
var secretKey = config.secretKey;
module.exports = function(api) {
api.route('/signup')
.post(function(req, res) {
var user = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password
});
user.save(function(err) {
if (err) res.send(err);
res.json({ message: 'user has been created'});
});
});
};
Try adding require('http') or require('https') as the first require statement.
I had the problem of var express = express() returning the error: not a function. After some spelunking in the express directories, I saw that the sample code required http or https first. So, add one (perhaps both) as first (and or second) file imports.
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
router.get('/', (req, res)=>{
res.send('Course Controller');
});
module.exports = router;
write npm i express -s
I've tried and it's working for me
When I set up the route for users in server.js and test with postman/localhost I get the error message, cannot GET /users. Same with any other crud operation. How can I fix this route?
server.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var mongoOp = require("./models/mongo");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
router.get("/",function(req,res){
res.json({"error" : false,"message" : "Hello World"});
});
router.route("/users")
.get(function(req,res){
var response = {};
mongoOp.find({},function(err,data){
// Mongo command to fetch all data from collection.
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
});
app.use('/',router);
app.listen(3000);
console.log("Listening to PORT 3000");
mongo.js
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/meanapi');
var mongoSchema = mongoose.Schema;
var userSchema = {
"userEmail" : String,
"userPassword" : String
};
module.exports = mongoose.model('userLogin', userSchema);
something helpful for these cases is to set NODE_ENV=development as an environment variable and use morgan. It prints out all the requests that hit your nodejs server with status code, method, path etc.
Here's a simple way to set it up:
if ('production' != app.get('env')) {
app.use(morgan('dev'));
}
Another thing that helps in debugging is
app.on('error', function (err) {
console.error(err); // or whatever logger you want to use
});
Ass that after all the middleware and it should print out if some requests fail to get all the way to your handlers.
Hope this helps!