I have an express API and there is a post route to create categories and products. But the post route is not functioning correctly. When I send a request to post route it's not reaching the route. However, when I send to get: /admin route it's reaching the route.
const express = require('express');
const { Category } = require('../models/categories');
const { Product } = require('../models/products');
const catchAsync = require('../utils/catchAsync')
const adminRouter = express.Router();
//Reaching this route
adminRouter.get('/', catchAsync(async(req, res)=>{
res.send({msg: 'HELLO'})
}))
//Not reaching at all
adminRouter.post('/category/create', catchAsync(async (req, res)=>{
const categoryData = req.body
console.log(req.body);
const category = await Category.create(categoryData);
res.status(201).json(category)
}))
adminRouter.post('/product/create', catchAsync(async(req, res)=>{
const productData = req.body
const product = await Product.create(productData);
res.status(201).json(product);
}))
module.exports = {adminRouter}
And this is my app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { adminRouter } = require('./routes/admin');
const app = express();
app.use(bodyParser.json({limit: "30mb", extended: true}))
app.use(bodyParser.urlencoded({limit: "30mb", extended: true}))
app.use(cors())
app.use('/admin', adminRouter)
module.exports = {app}
This is what I get when I send request from Postman
As you can see no status code and no response body. However when I send request to get route it's returning correct response.
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.
i have a problem when POST some data in POSTMAN my problem is during "post" method /auth/login req.body return empty array.
Postman return empty object only if i use POST method with use form-data, if i change to xxx-www-form-urlencoded whatever works fine. I wanna know why it works so
const express = require('express');
const mongoose = require('mongoose');
const app = express();
require('dotenv').config();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/static", express.static(__dirname + "/assets"))
app.post('/auth/login', (req, res) => {
res.status(200).json(req.body)
})
mongoose.connect("mongodb://localhost:27017")
.then(() => {
app.listen(port, () => {
console.log('port' + port)
})
})
I'm assuming you mean application/x-www-form-urlencoded instead of xxx-www-form-urlencoded and you mean multipart/form-data instead of form-data.
These 2 content-types are completely different encodings. When you called:
app.use(express.urlencoded({ extended: true }));
You added a middleware that can parse application/x-www-form-urlencoded, but that does not mean it automatically parses other formats too. It's only for that format, just like express.json() is only for the application/json format.
I solved this, i just created multer in my controller and it work how i wanted
const express = require('express');
const router = express.Router();
const { getUsers, createNewUser } = require('../controllers/newUser')
const path = require('path');
const multer = require('multer');
const upload = multer();
router.get('/', getUsers)
router.get('/:id', (req, res) => res.send('get single user'))
router.post('/', upload.none(), createNewUser)
module.exports = router;
I have a node express set up.
While using Postman, Iam able to see data sent through x-www-form-urlencoded but the same is not being shown through form-data.
below are the codes
Server.js
const express = require('express')
var cors = require('cors')
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.use(cors())
const index = require("./routes/index")
app.use("/", index)
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() { console.log(`Running on ${port}`) });
Index.js
const express = require('express')
const router = express.Router()
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const func = require('./functions')
const time = new Date().toISOString().slice(0, 19).replace('T', ' ')
const nodemailer = require("nodemailer");
router.use('/auth', require('./auth')
Auth .js
const express = require('express')
const router = express.Router();
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const nodemailer = require("nodemailer");
const func = require('./functions')
router.post('/register', asyncMiddleware( async(req, res, next) => {
res.send({ success: true, message: req.body })
}))
You should use Multer to handle form-data.
Multer is a node.js middleware for handling multipart/form-data
body-parser middleware can't handle multipart/form-data.
This does not handle multipart bodies, due to their complex and typically large nature.
In case you need to handle a text-only multipart form, you should use the .none() method:
E.g.
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const app = express();
app.use(upload.none());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/auth/register', (req, res) => {
res.send({ success: true, message: req.body });
});
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() {
console.log(`Running on ${port}`);
});
postman:
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);
});
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.