I am new to React and Node and I'm getting an undefined token in console when I add category I get undefined in the console. I am using cookie-parser.
server.js file:
const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const cookieParser = require('cookie-parser')
const connectDB = require('./database/db');
const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
//middleware
app.use(cors());
//dev specifies it is for development
app.use(morgan('dev'));
//express.json allows us to parse incoming request in json in the format of a json
app.use(express.json());
app.use(cookieParser());
app.use('/api/auth', authRoutes);
//route for category
app.use('/api/category', categoryRoutes);
connectDB();
app.get('/', (req,res) => {
res.send('Inside Server');
});
const port = process.env.PORT || 5000;
app.listen(port, ()=>console.log(`Listening on port ${port}`));
category.js (controller file)
exports.create = (req,res) => {
setTimeout(()=> {
res.json({
successMessage: `${req.body.category} was created!`
});
}, 5000);
};
category.js (routes file)
const express = require('express');
const router = express.Router();
const categoryController = require('../controllers/category');
const { authenticateJWT } = require('../middleware/authenticator');
router.post('/', authenticateJWT , categoryController.create);
module.exports = router;
authenticator.js (middleware file)
const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/keys');
exports.authenticateJWT = (req, res, next) => {
const token = req.cookies.token;
console.log(token);
}
keys.js file
//it is gonna tell us/ signifying if we are live if in develoopment or in production
const LIVE = false;
if (LIVE) {
module.exports = require('./prod.js');
} else {
module.exports = require('./dev.js');
}
Console screen:
Instead of undefined i should be getting token.
Any help will be highly appreciated.
Thanks!
Is there a token Cookie available? (You can check using the inspector of your browser, normally in the βapplicationβ tab. If you are sending the request using any tools like postman, curl, wget, β¦, you have to set the cookie first.)
Was the cookie available on any other routes? Whatβs the difference between these routes and the category route? Is it possible that your cookie is constrained to a specific path, e.g. to /api/auth? If so, adjust the path in res.cookie.
Related
Okay so i just started building an api using Node. Normally, before i even start, i test it in the postman using dummy data to make sure all the routes are working fine but i never tested it on the browser until today. It brings out the dummy data all fine in the postman but when I put in the same route i used in the postman on the browser tab, it just brings out my custom error message "Route does not exist". Why is this happening?
This is my routes/auth.js
const express = require('express')
const router = express.Router()
const {upload} = require('../utils/multer')
const { register, login } = require('../controllers/auth')
router.post('/register', upload.single('picture'), register)
router.post('/login', login)
module.exports = router
This is my controllers/auth.js:
const register = async (req, res) => {
res.send('register')
}
const login = async (req, res) => {
res.send('login')
}
module.exports = {register, login}
This is my app.js:
require('dotenv').config()
require('express-async-errors');
const bodyParser = require('body-parser')
const cors = require('cors')
const multer = require('multer')
const helmet = require('helmet') //helps you secure your Express apps by setting various HTTP headers.
const morgan = require('morgan')
const path = require('path')
const express = require('express');
const app = express();
/* CONFIGURATIONS */
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(express.urlencoded({ limit: "30mb", extended: true }));
app.use("/assets", express.static(path.join(__dirname, "public/assets")));
//routers
const authRouter = require('./routes/auth')
// error handlers
const notFoundMiddleware = require('./middleware/not-found');
const errorHandlerMiddleware = require('./middleware/error-handler');
//middleware
app.use(express.json());
app.use(cors());
//routes
app.use('/api/v1/auth', authRouter)
//errors
app.use(notFoundMiddleware);
app.use(errorHandlerMiddleware);
//database
const connectDB = require('./db/connect');
const port = process.env.PORT || 5000;
const start = async () => {
try {
await connectDB(process.env.MONGO_URI);
app.listen(port, () =>
console.log(`Server is listening on port ${port}...`)
);
} catch (error) {
console.log(error);
}
};
start();
Please note that i do not understand what most of these configurations do, not very well anyways. i have tried to remove them though but the problem was still there.
I am assuming you are trying to access /login or /register route from browser search bar something like this http://host:port/login. With this browser will send GET /login request but /login is a POST method route that is the reason you are getting Route not found
When you send request from your browser then by default it will send GET request and your app is not handling GET requests.
You are handling POST requests for /register and /login routes.
Currently I have a public api implemented, anyone can access it.
My intention is that the user now pass a token through the header so that they can access the data from the endpoints. But I don't know how to implement it in my code.
I appreciate your help!
router.get('/AllReports' , (req , res) =>{
PluginManager.reports()
.then(reports =>{
res.status(200).json({
reports
});
}).catch((err) =>{
console.error(err);
});
});
app.js
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser');
const middlewares = require('./middlewares/index').middleware;
const api = require('./api');
const app = express();
app.use(morgan('dev'));
app.use(helmet());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.json({
message: 'π¦πβ¨ππππβ¨ππ¦'
});
});
app.use('/api/v1', api);
app.use(middlewares);
module.exports = app;
To see a list of HTTP request headers, you can use :
console.log(JSON.stringify(req.headers));
Then you can check if token is valid and then
go on with processing.
Example
router.get('/', (req, res) => {
// header example with get
const authHeader = req.get('Authorization'); //specific header
console.log(authHeader);
// example with headers object. // headers object
console.log(req.headers);
});
My problem
I am trying to write a register/login page in node.js using express.js. I have decided to split routes and app initialization into two files. When I send a POST request to localhost:3000/register with the data {"username":"xyz","password":"xyz"}, the request object has the attribute body. However when I try to access this attribute, I get undefined.
My current code
// app.js
// Load express and define port
const express = require('express');
const app = express();
const port = 3000;
// App Configurations
app.use(express.json())
// Load Routes
var registerRouter = require('./controllers/register.js');
// Use Routes
app.use('/register', registerRouter);
// Start App
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
// controllers/register.js
// requires
var argon2i = require('argon2-ffi').argon2i;
var bodyParser = require('body-parser');
var {Database, Model} = require('mongorito');
var crypto = require('crypto')
var Promise = require('bluebird');
var randomBytes = Promise.promisify(crypto.randomBytes);
var express = require('express');
// define router
var router = express.Router();
// Mongo Connection
const db = new Database('localhost/test', {
reconnectTries: 5
});
// Models
class User extends Model {}
// Register Models
db.register(User);
// Routes
router.post('/', async (res, req) => {
console.log(req.body);
if(!req.body) return req.sendStatus(400);
const username = req.body.username;
const salt = randomBytes(32);
const password = argon2i.hash(req.body.password, salt);
var user = new User({
username: username,
password: password,
salt: salt
});
await user.save;
res.send("User Created");
});
// Disconnect From Database
db.disconnect;
//export router
module.exports = router;
My expected result
I expect to be able to access req.body and req.body.username.
You have a small issue in you code. The router.post callback function first parameter is req and the second is res. The Callback function parameters are fixed not named parameters.
You are trying to get the body on the response object, though the name of the parameter is req but it still holds the response object. which is causing the issue.
Please change it.
Wrong:
router.post('/', async (res, req) => {
Correct:
router.post('/', async (req, res) => {
I see you are importing bodyParser in controller/register but not setting it, at least in this snippet. if you do not have any special reasons for putting it in the controller, then do this instead.
// app.js
// Load express and define port
const express = require('express');
const bodyParser = require('body-parser'); // new code
const app = express();
app.use(bodyParser.urlencoded({ extended: true })); // new code
const port = 3000;
// App Configurations
app.use(express.json())
// Load Routes
var registerRouter = require('./controllers/register.js');
// Use Routes
app.use('/register', registerRouter);
// Start App
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I'm new to express and node js, I recently learned how to write API for express but at the end, I get some sort of problem which not resolved by me after several tries. I could not get a response on localhost:8080/users
src/routes/users.js
const { Router } = require("express");
const router = Router();
const getUsers = (req, res) =>
res.send(Object.values(req.context.models.users));
const getUser = (req, res) =>
res.send(req.context.models.users[req.params.userId]);
router.get("/users/", getUsers);
router.get("/users/:userId", getUser);
module.exports = router;
src/routes/index.js
const user = require("./user");
const message = require("./message");
module.exports = {
user,
message
};
src/index.js
const express = require("express");
const app = express();
// Custom Modules
const routes = require("./routes");
const models = require("./models");
// Application-Level Middleware Starts
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
req.context = {
models,
me: models.users[1]
};
console.log(req.context.models.users);
next();
});
// Used Routes
app.use("/users", routes.user);
app.use("/messages", routes.message);
// App Listning to HTTPS Module
app.listen(process.env.PORT);
You need to fix your endpoints in users.js:
router.get("/", getUsers);
router.get("/:userId", getUser);
The reason is because of app.use("/users", routes.user); in your index.js, where the endpoint for users is set. If you leave /users/ in users.js it would be localhost:8080/users/users/. Same problem might be with /messages.
I'm working on a project and I have seeded some data. But when I try to do any request to my localhost I get this error:
// 20170624132844
// http://localhost:4310/campuses
{
"code": "ECONNREFUSED",
"errno": "ECONNREFUSED",
"syscall": "connect",
"address": "127.0.0.1",
"port": 5432
}
my requests were working prior to me restarting my computer, not sure what is happening here. Can someone please explain what the error means and how to handle it.
I'm including my app.js code here in case it would help.
'use strict';
if(process.env.NODE_ENV !== 'production'){
require('dotenv').config();
}
//use npm install cors - this stands for Cross- origin resouce sharing
const express = require('express');
const app = express(), bunyanLogger = require('express-bunyan-logger');
const PORT = process.env.PORT;
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const Bunyan = require('bunyan');
const compress = require('compression');
const cohortsRoute = require('./routes/cohorts');
const campusesRoute = require('./routes/campuses');
const usersRoute = require('./routes/users');
const skills = require('./routes/skills');
const morgan = require('morgan');
switch (app.get('env')) {
case 'development':
app.use(morgan('dev'));
break;
case 'production':
app.use(morgan('short'));
break;
default:
}
app.use(bodyParser.json());
app.use(express.static(path.join('public')));
// app.use('/api/authenticate', authenticateController.authenticate)//from video tutorial.
//other modules that might need to be required later
// const users = require('./routes/users');
// const admin = require('./routes/admin');
// const cohorts = require('./routes/cohorts');// already up there.
// const campus = require('./routes/campus');
// const projects = require('./routes/projects')
// const skills = require('./routes/skills');
// const profile = require('./routes/profile');
// app.use(users)
app.use(campusesRoute);
app.use(cohortsRoute);
app.use(usersRoute);
// app.use(campus)
// app.use(projects)
app.use(skills)
app.use((req, res) => {
res.sendStatus(404);
});
app.get('/', function(req, res) {
res.send('Hello World, Ivonne at work here');
res.send(path.resolve(__dirname, 'buil'))
});
app.listen(PORT, () => {
if(app.get('env') !== 'test'){
console.log(`Galvanize Connect server listening on port ${PORT}`);
}
});
module.exports = app;