Been stuck on this over an hour or two now >.<
I am unable to access the request body for the user api. I can get the response 'hi' back using res.send (see screenshot) but not with any req.body values. Email is coming back undefined :/
Any ideas where I am going wrong?
Content type is set to json on the postman headers.
Controller:
import asyncHandler from 'express-async-handler'
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body
res.send('hi' + email)
})
export {authUser}
Route:
import express from 'express'
const router = express.Router()
import { authUser } from '../controllers/userController.js'
router.post('/login', authUser)
export default router
hiundefined ^
Server.js
import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js'
import productRoutes from './routes/productRoutes.js'
import userRoutes from './routes/userRoutes.js'
import colours from 'colours'
import { notFound, errorHandler} from './middleware/errorMiddleware.js'
dotenv.config()
connectDB()
const app = express()
app.use(express.json())
app.get('/', (req, res) => {
res.send('API is running...')
})
app.use('/api/products/', productRoutes)
app.use('/api/users/', userRoutes)
app.use(notFound)
app.use(errorHandler)
const PORT = process.env.PORT || 5000
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold)
)
Headers:
use this middleware because if you are using Express 4.16+ you can app.use(express.json())
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyparser.json());
and update your header request accept Content-Length : <calculated when request is sent>
``
I believe you need to pass the request req through to your authUser function
router.post('/login', (req, res) => {
authUser(req, res)
});
Related
I have finished Nodejs express app and I want to deploy it to Firebase functions when I run firebase emulator.
I am not able to reach my app.use routes.
I am able to reach
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
This is my index.js in functions
import functions from 'firebase-functions';
import app from '../app.js';
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
export const invest = functions.https.onRequest(app);
my app.js
import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import mongoSanitize from 'express-mongo-sanitize';
import xss from 'xss-clean';
import hpp from 'hpp';
import path from 'path'
import AppError from './utils/appError.js';
import companyRouter from './routs/company.js'
import userRouter from './routs/user.js'
const app = express();
app.use(cors());
// 1) GLOBAL MIDDLEWARES
// Set security HTTP headers
app.use(helmet());
// Development logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// app.use(bodyParser({
// json: { limit: '50mb', extended: true },
// urlencoded: { limit: '50mb', extended: true }
// }));
// Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!'
});
app.use('/api', limiter);
// Body parser, reading data from body into req.body
app.use(express.json({ limit: '250kb' }));
// Data sanitization against NoSQL query injection
app.use(mongoSanitize());
// Data sanitization against XSS
app.use(xss());
// Prevent parameter pollution
app.use(
hpp({
whitelist: []
})
);
// Serving static files
// app.use(express.static(`${__dirname}/public`));
// Test middleware
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
// console.log(req.headers);
next();
});
// app.use(express.static(path.resolve('../client/build')));
// app.get('*', (req, res) => {
// res.sendFile(path.resolve('../client/build', 'index.html'));
// });
// // 3) ROUTES
app.use('/api/v1/companies', companyRouter);
app.use('/api/v1/users', userRouter);
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
// app.use('/api/v1/reviews', reviewRouter);
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
// app.use(globalErrorHandler);
export default app;
My router
company.js
import express from 'express';
import {getAllCompanies, getOneCompany, createCompany, updateCompany, deleteCompany, likeCompany, newPrice, GetAllPrices} from '../controllers/company.js'
import { protect } from '../controllers/auth.js'
import { createNews, getAllNews } from '../controllers/newsController.js';
const router = express.Router();
router.get('/', getAllCompanies);
router.get('/ir', getAllNews);
router.get('/myAccount', GetAllPrices);
router.get('/:id', getOneCompany);
router.post('/', createCompany);
router.post('/myAccount', newPrice);
router.post('/ir', createNews);
router.patch('/:id/likeCompany',protect, likeCompany);
router.patch('/:id', updateCompany);
router.delete('/:id', deleteCompany)
export default router;
I get local address
http://localhost:5001/investfouyou/us-central1/invest
and that gets me
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
but I need to get
http://localhost:5001/investfouyou/us-central1/invest/api/v1/companies
to access my router
I want to get to these two lines
app.use('/api/v1/companies', companyRouter);
app.use('/api/v1/users', userRouter);
Please help
Here is my server.js:
import express from "express";
import mongoose from "mongoose";
import productRouter from "./routers/productRouter.js";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(express.json());
let prof = process.env.PROF;
mongoose.connect(
`${prof}`
);
// Add headers before the routes are defined
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "*");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.header("Access-Control-Allow-Headers", "Content-Type");
// Request headers you wish to allow
// res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
/*
app.get("/api/products", (req, res) => {
res.send(data);
});*/
app.use("/api/products", productRouter);
app.get("/", (req, res) => {
res.send("Server is ready");
});
const port = process.env.PORT || 5000;
app.listen(port);
Going inside productRouter.js ...
import express from "express";
import mongoose from "mongoose";
import data from "../data.js";
import Product from "../models/productModel.js";
import { payment } from "./paymentController.js";
const productRouter = express.Router();
productRouter.use("/pay", async (req, res, next) => {
// dont store cart in db, store it in local storage. On checkout get Id of all items in cart. Then find their prices from the db and charge correctly.
console.log("middleware ran");
console.log(req.body);
const productIdsAndAmounts = req.body.basketItems.items.map((item) => {
return { id: item.id, amount: item.amount };
});
// this works faster (apparently)
/*
const objIds = productIds.map((id) => mongoose.Types.ObjectId(id));
const orderedItems = await Product.find({
_id: { $in: objIds },
});
*/
// this sends more query requests to db
const orderedItems = await Promise.all(
productIdsAndAmounts.map((productId) => {
return Product.findById(productId.id);
})
);
let i = -1;
let productIdsPricesAmounts = [];
orderedItems.forEach((item) => {
i = i + 1;
productIdsPricesAmounts.push({
id: item.id,
price: item.price,
amount: productIdsAndAmounts[i].amount,
});
});
console.log(productIdsPricesAmounts);
const prices = productIdsPricesAmounts.map((item) => {
return item.price * item.amount;
});
const reducer = (prevValue, currValue) => prevValue + currValue;
const totalTotalPrice = prices.reduce(reducer);
console.log(totalTotalPrice);
req.totalPrice = totalTotalPrice;
//console.log(orderedItems);
//console.log(productIdsAndAmounts);
// console.log(req.body.user); // adres
next();
});
productRouter.get("/", async (req, res) => {
const products = await Product.find({});
res.send(products);
});
productRouter.post("/pay", payment);
export default productRouter;
Now to the paymentController.js:
export const paymentController = async (req, res, next) => {
console.log(req.body.basketItems)
/* returns contents of the body like expected, i can do whatever i want with it*/
}
The behaviour, i can get is:
Client sends request to "api/products/pay", i have access to req.body in paymentController.
The behaviour, i want is:
Client sends request to "api/products/pay", the request first goes through a middleware where i do some calculations on it, then i forward the new variable to my paymentController. The problem is req.body is {} in middleware productRouter.use(), but available in paymentController
What am I doing wrong ? I'm new to express and i don't exactly know what I'm doing yes. I want to have access to req.body inside productRouter. I'm guessing i set up the middleware wrong or something like that. But I can't see what i did wrong.
Can You Use
Router For Example :
user.ts
import express from "express";
let UserRoute = express.Router()
UserRoute.get('/',function (req,res) {
res.json('Hello World')
})
export { UserRoute }
App.ts
import express from "express";
import cors from "cors";
import { UserRoute } from "./routes/v1/user"
const http = require('http');
const app = express();
const server = http.createServer(app);
const PORT : string|number = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use('/',UserRoute)
//Run Server And Listen To Port
server.listen(PORT,()=>{
console.log("Server UP")
})
Guess this is your main route where you want to add middleware function right
Create a middle were function with name "abc" export from there as name "abc"
Now, here in main route you can use that function as a middleware
productRouter.post("/pay",abc, payment);
here abc is your middleware function
How to fetch cookies value from client service to server service in react js?
The cookie successfully stored on the clent side but when i am trying console from server side it is showing undefined .
please help me !!
index.js (server side):
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
const app = express();
import cookieParser from "cookie-parser";
import connection from "./database/db.js";
import Router from "./routes/route.js";
import auth from "./middleware/auth.js";
const corsOptions = {
origin: true, //included origin as true
credentials: true, //included credentials as true
};
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(bodyParser.json({ extended: true }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/', Router);
app.use(express.json());
const PORT = 8000;
app.listen(PORT, () => {
console.log(`server is running successfully at ${PORT}`);
})
connection();
Auth.js (Authentication middleware(server side)):
import jwt from 'jsonwebtoken';
import post from '../schema/post-schema.js'
import profile from '../schema/profile-schema.js';
const auth = async (req, res, next) => {
try {
const token = req.cookies['jwt'];
console.log("The token is", token) //it shows undefined
const verifyuser = jwt.verify(token, "mynameismohitkumarfromnationalinstituteoftechnologyagartala");
const user = await profile.findOne({ _id: verifyuser._id });
console.log(verifyuser);
console.log(user);
next();
} catch (error) {
res.status(401).json(error);
}
}
export default auth;
Have a look at cookie options if the cookie is HttpOnly then you cant read the cookie from the client-side.
So am trying to create a RESTful api with express and nodejs. When i run npm start to start the server it throws an error saying Router.use() requires a middleware but got an undefined. Any ideas what could be the problew. My code is pasted below.
Thanks in advance
server.js
import express from 'express';
import bodyParser from 'body-parser';
import { router as Orders } from './routes/order';
const app = express();
// PORT Number
const PORT = process.env.PORT || '3000';
// Setting up the body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Setting up middleware for a specific route
app.use('/api', Orders);
app.listen(PORT, () => {
console.log(`Running application on port ${PORT}`);
});
order.js route
import express from 'express';
const router = express.Router();
router.get('/', (req, res, next) => {
res.send('Hello from api');
next();
});
export default router;
When using a default export:
export default router;
You should be importing it using the syntax:
import Orders from './routes/order'
Or, if you want to keep the import syntax the same, you can change the export so that it is not a default:
export { router }
I just starting to use node.js to build a RESTFul api. I'm now trying to insert data by post with json in body.
But when I try to get req.body always got undifined.
So I check at here. Saw some people said that the express configuration should before the route.
After I modified my code. I can't even get home page.
Can anyone help me solve this problem?
express.js before
/* express.js */
import bodyParser from 'body-parser';
import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import config from './config';
import index from '../server/routes/index.route';
const app = express();
/* GET home page. */
app.get('/', (req, res) => {
res.send(`server started on port.. http://127.0.0.1:${config.port} (${config.env})`);
});
app.use('/api', index);
// parse body params and attache them to req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors);
// Http request logger
app.use(morgan('dev'));
export default app;
POST RESULT
{
"code": "ER_PARSE_ERROR",
"errno": 1064,
"sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "INSERT INTO Article SET ?"
}
express.js after
/* express.js */
/* ... */
const app = express();
// parse body params and attache them to req.body
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors);
// Http request logger
app.use(morgan('dev'));
/* GET home page. */
app.get('/', (req, res) => {
res.send(`server started on port.. http://127.0.0.1:${config.port} (${config.env})`);
});
app.use('/api', index);
export default app;
index.js
import config from './config/config';
import app from './config/express';
if (!module.parent) {
// listen on port config.port
app.listen(config.port, () => {
console.log(`index.js >>> server started on port http://127.0.0.1:${config.port} (${config.env})`);
});
}
export default app;
index.route.js
import express from 'express';
import mysql from 'mysql';
import article from './article.route';
import config from './../../config/config';
const router = express.Router();
/* GET localhost:[port]/api page. */
router.get('/', (req, res) => {
res.send(`此路徑是: localhost:${config.port}/api`);
});
/* mysql連線測試 */
router.get('/sqlTest', (req, res) => {
const connectionPool = mysql.createPool({
connectionLimit: 10,
host: config.mysqlHost,
user: config.mysqlUserName,
password: config.mysqlPass,
database: config.mysqlDatabase
});
connectionPool.getConnection((err, connection) => {
if (err) {
res.send(err);
console.log('連線失敗!');
} else {
res.send('連線成功!');
console.log(connection);
}
});
});
// article router
router.use('/article', article);
export default router;
article.route.js
const router = express.Router();
router.route('/').post(articleCtrl.articlePost);
article.controller.js
const articlePost = (req, res) => {
const insertValues = req.body;
console.log('insertValues ', insertValues);
articleModule.createArticle(insertValues).then((result) => {
res.send(result);
}).catch((err) => { return res.send(err); });
};
you need to call bodyParser.json and cors as a function; app.use(bodyParser.json());, app.cors()