I am just starting out with nodejs backend, so this might be a stupid question.
Little info
I got my client (localhost:8080) and my server.js (localhost:3000). I made some routes for my server.js (see the file below).
Question
Now, if I try to access the route on my server e.g. localhost:3000/users/4, I get the expected result - 4 fake users are created. However if I try to append the postfix users/4 to the client: (localhost:8080/users/4), I get an error! Cannot GET /users/4. Likewise I get an cannot GET *SOMETHING* if I try one of the other routes.
Have I misinterpreted something? Shouldn't I be able to append the route to the client url and then get the res (respons) back again? (as long as the server is running of course, or is that not how it works?). It would be lovely if someone could clarify how it works.
routes.js (I got all my routes in this one file)
var faker = require("faker");
var appRouter = function (app) {
app.get("/", function (req, res) {
res.status(200).send({ message: 'Welcome to our restful API' });
});
app.get("/user", function (req, res) {
var data = ({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.internet.userName(),
email: faker.internet.email()
});
res.status(200).send(data);
});
app.get("/users/:num", function (req, res) {
var users = [];
var num = req.params.num;
if (isFinite(num) && num > 0 ) {
for (i = 0; i <= num-1; i++) {
users.push({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.internet.userName(),
email: faker.internet.email()
});
}
res.status(200).send(users);
} else {
res.status(400).send({ message: 'invalid number supplied' });
}
});
};
module.exports = appRouter;
Server.js
var express = require("express");
var bodyParser = require("body-parser");
var routes = require("./routes/routes.js");
var app = express();
const server_port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
routes(app);
var server = app.listen(server_port, function () {
console.log("app running on port.", server.address().port);
});
For me this works fine at (for example): http://127.0.0.1:8081/testit/35 ::
app.get('/testit/:bid', function(req, res){
res.send('testit' + req.params.bid);
});
I would recommend, that you reduce your problem. So, start small with a route similar to mine and build from there.
Related
I'm new in couchbase and I'm using ottoman framework. I connected the database using ottoman and I create the schema and model User and exported it into controller file. When I create a new instance for that model, ottoman throw an error TypeError: User is not a constructor.
I search so many time and I red the official and non official documents and test it severely. I wrote all about the db in separate file and no change. I'll attach the file below it . But I didn't get any solution. please let me know...
const ottoman = require("ottoman");
exports.connect = async () => {
try {
await ottoman.connect({
connectionString: process.env.DB_CONNECTION_STRING,
bucketName: process.env.DB_BUCKET,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
});
console.log("Database connected.");
await ottoman.start();
} catch (error) {
console.log("Database not connected due to: ", error.message);
}
};
connect();
const User = ottoman.model("User", {
firstName: String,
lastName: String,
email: String,
tagline: String,
});
const perry = new User({
firstName: "Perry",
lastName: "Mason",
email: "perry.mason#example.com",
tagLine: "Who can we get on the case?",
});
const tom = new User({
firstName: "Major",
lastName: "Tom",
email: "major.tom#example.com",
tagLine: "Send me up a drink",
});
main = async () => {
await perry.save();
console.log(`success: user ${perry.firstName} added!`);
await tom.save();
console.log(`success: user ${tom.firstName} added!`);
};
main();
This issue happened due to disorder of functions calling in app.js file. All I used till now was a Mongodb and mongoose in noSQL. In the case of mongodb we can call the database config function after api endpoint specification. I wrote my code like this in couchbase. But it didn't stick in couchbase. I'll provide my code before and after fixing for more clarity, and I'm very sorry for my bad english. :)
Before fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// database setup
const db = require("./config/db");
db.connect();
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
After fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// database setup
const db = require("./config/db");
db.connect();
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);
I am working on an educational project from udemy, by dr. yu. I am trying to add content via post request. I keep getting undefined.
From what I can tell, most solutions are user error based with post request and make sure postman form encoded option is checked, or not using body-parser. Both of those seem to be okay on my end.
The code successfully adds content, just, it's empty. Any tips?
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
const app = express();
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB", { useNewUrlParser: true });
const articleSchema = {
title: String,
content: String,
};
const Article = mongoose.model("Article", articleSchema);
app.get("/articles", function (req, res) {
Article.find(function (err, foundArticles) {
if (!err) {
res.send(foundArticles);
} else {
res.send(err);
}
});
});
app.post("/articles", function (req, res) {
const newArticle = new Article({
title: req.body.title,
content: req.body.content,
});
newArticle.save(function (err) {
if (!err) {
res.send("Successfully added a new article.");
} else {
res.send(err);
}
});
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function () {
console.log(`Server started on port ${port} successfully`);
});
I want to create a simple RESTful service for managing the list of genres of movies. First I tried to handle all the HTTP requests to a given route('/api/genres') in a single file (server.js), and my code worked, i.e I was able to Post movies, update movies when I handled the routes from the main server.js file. But then, I tried to handle the routes in a separate file, but I'm getting problems.
Problems:
It seems my movies variable from server.js has not been able to export itself, as, I'm getting 'undefined' on console.log(movies) in generes.js. So for post and put request, nothing is being displayed
I have read that router.get and app.get are not much different, still, app.get doesn't work in genres.js
Server.js
const app = express();
const generes = require("./routes/api/genres");
app.use(express.json());
var movies = [
{
name: "harry potter",
genere: "fiction"
},
{
name: "IT",
genere: "horror"
},
{
name: "chicchore",
genere: "comedy"
},
{
name: "A walk to remember",
genere: "romantic"
}
];
app.use("/api/genres", generes);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log("Server running..."));
module.exports.movies = movies;
genres.js
var express = require("express"),
app = express();
const server = require("../../server");
const router = express.Router();
app.use(express.json());
//importing movies array
var movies = server.movies;
router.get("/", (req, res) => {
res.send(movies);
});
router.post("/", (req, res) => {
var movie_obj = {
name: req.body.name,
genere: req.body.genere
};
movies.push(movie_obj);
res.send(movie_obj);
});
router.put("/:id", (req, res) => {
var flag = 0;
movies.forEach(ele => {
if (ele.name == req.params.id) {
ele.name = req.body.name;
flag = 1;
res.send(movies);
}
});
//if (flag == 0) res.send(`no such movie exists ${req.params.id}`);
});
module.exports = router;
function newFunction() {
return "movies";
}
Also,When I used app.get instead of router.get. I got the following error:
-> this is my server.js. while i am trying to open it by using node server, it is showing cannot get/.
-> as i am trying to open. it is showing cannot get/. I have routed all the links correctly. but still this issue is pertaining me.
-> in my server it is showing mongodb connected and running. but whilw i open it it is showing cannot get/
var express = require('express');
var bodyParser = require('body-parser');
var User = require('./app/models/user');
var app = express();
var jwt = require('jwt-simple') var _ = require('lodash') var bcrypt = require('bcrypt')
app.use(bodyParser.json()); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
var secretkey = "supersecretkey"
app.post('/session', function(req, res, next) {
console.log(req.body.username);
User.findOne({
username: req.body.username
}).select('password').exec(function(err, user) {
if (err) {
return next(err)
}
if (!user) {
return res.send(401)
}
bcrypt.compare(req.body.password, user.password, function(err, valid) {
if (err) {
return next(err)
}
if (!valid) {
return res.send(401)
} //var test = {username:user.username}; //console.log(user.username); var token = jwt.encode({ username: req.body.username}, secretkey) res.json(token)
})
})
})
app.get('/user', function(req, res, next) {
var token = req.headers['x-auth'] console.log(token)
var auth = jwt.decode(token, secretkey)
//console.log(auth)
User.findOne({ username: auth.username
}, function(err, user)
{ res.json(user) }) })
app.post('/user', function(req, res) {
var user = new User({
username: req.body.username
}) bcrypt.hash(req.body.password, 10, function(err, hash) {
user.password = hash user.save(function(err, user) {
if (err) {
throw next(err)
} // res.send(201) res.json(user); }) })
})
app.listen(3000)
->This is my app.js.
"use-strict"
var express = require('express');
var router = express.Router(); // get an instance of the express Router
var morgan = require('morgan');
var bodyParser = require('body-parser');
var app = express();
/*app.use(morgan('dev'));*/
app.use('/public/app/controllers/routes', router);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({
extended: true
})); // support encoded bodies
app.use(require('./config/auth'))
app.use('/api/users', require('./app/controllers/api/users'))
app.use('/api/sessions', require('./app/controllers/api/sessions'))
app.use('/api/products', require('./app/controllers/api/products'))
app.use('/api/companies', require('./app/controllers/api/companies'))
app.use('/api/stockists', require('./app/controllers/api/stockists'))
app.use('/api/employees', require('./app/controllers/api/employees'))
app.use('/api/sales', require('./app/controllers/api/sales'))
app.use('/', require('./app/controllers/static'))
var port = process.env.PORT || 3000
var server = app.listen(port, function() {
console.log('App listening at the ', port);
});
require('./websockets').connect(server)
-> as i am trying to open. it is showing cannot get/. I have routed all the links correctly. but still this issue is pertaining me.
-> in my server it is showing mongodb connected and running. but whilw i open it it is showing cannot get/