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:
Related
I created an API with node js express that works on localhost perfectly. but when I upload on the Cpanel just / route work and when I call another route that redirect to / route again
this is my server.js file
const http = require("http");
const express = require("express");
const app = express();
require("dotenv").config();
const helmet = require("helmet");
const bodyParser = require("body-parser");
const { nanoid } = require("nanoid/async");
const cors = require("cors");
//middleware
//json body
app.use(bodyParser.json());
//urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
//helmet
app.use(helmet());
app.use("/upload", express.static(process.cwd() + "/upload"));
const corsOptions = {
origin: "*",
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
const userRoute = require("./routes/userRoute");
app.use("/user", userRoute);
const provinceRoute = require("./routes/provinceRoute");
app.use("/province", provinceRoute);
const adverbRoute = require("./routes/adverbRoute");
app.use("/adverb", adverbRoute);
const catSubRoute = require("./routes/catSubRoute");
app.use("/category", catSubRoute);
const uploadRoute = require("./routes/upload");
app.use("/upload", uploadRoute);
app.use('/',(req,resp)=>{
resp.status(200).send("ok");
})
const server = http.createServer(app);
server.listen(process.env.PORT, () => {
console.log("server is running...");
});
module.exports = app;
and this is a route that I called with this URL
https://example.com/api/category/getallcats
const express = require("express");
const router = express.Router();
const catSubController = require("../controllers/catSubController");
router.get("/getallcats", catSubController.getAllCats);
module.exports = router;
and this return ok the same
https://example.com/api/ return ok on result
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.
I am lost as to why req cookies are always undefined in the expressJS. Here is my code:
const accessToken = jwt.sign({id:user._id}, process.env.JWT_TOKEN_SECRET)
console.log(accessToken)
res.cookie('authcookie',accessToken)
console.log(req.cookies.authcookie)
Here is the server.js code:
const express = require("express");
const app = express();
const morgan = require('morgan');
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser');
const path = require('path');
const userRoute = require('./routes/user')
dotenv.config()
const port = process.env.PORT || 5000
app.use(cors());
app.use(cookieParser())
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
app.use('/api', userRoute)
Where did I go wrong? Many thanks in advance and greatly appreciate any helps. Thanks
Here is a working example:
server.js:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
process.env.JWT_TOKEN_SECRET = 'secret';
const port = process.env.PORT || 5000;
app.use(cors());
app.use(cookieParser());
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/auth', (req, res) => {
const user = { _id: '123' };
const accessToken = jwt.sign({ id: user._id }, process.env.JWT_TOKEN_SECRET);
res.cookie('authcookie', accessToken);
res.sendStatus(200);
});
app.get('/api', (req, res) => {
console.log(req.cookies);
jwt.verify(req.cookies.authcookie, process.env.JWT_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log(err);
res.sendStatus(500);
return;
}
console.log('decoded jwt: ', decoded);
res.sendStatus(200);
});
});
app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));
Open your browser with the http://localhost:5000/auth URL to get the authcookie cookie. Then access http://localhost:5000/api URL to call the api.
Output in the console:
HTTP server is listening on http://localhost:5000
GET /aut 404 2.095 ms - 142
GET /auth 200 4.047 ms - 2
{
authcookie: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMyIsImlhdCI6MTYxODgxODMyM30.mwCmW2NKSE9Youppnq_SCft7snYSp1Ud7nTThi7Q6Os'
}
decoded jwt: { id: '123', iat: 1618818323 }
GET /api 200 3.856 ms - 2
I have a problem with my post data to the server. Not sure why i get an error for get when i changed my rout to post.
routes/feedback.js
const express = require("express");
const router = express.Router();
const { emailFeedback } = require("../controllers/feedback");
router.post("/feedback", emailFeedback);
module.exports = router;
server.js
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
// import routes
const feedbackRoutes = require("./routes/feedback");
// app
const app = express();
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cors());
// routes
app.use("/api", feedbackRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
I believe the usual syntax for an express post route is as follows:
router.post("/feedback", function(req, res){
//grabbing the request body
console.log(req.body);
console.log(req.bodt);
//posting the request
res.json(req.body);
});
A callback function needs to be passed in and receive those request and response parameters (req, res).
I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.