Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 days ago.
Improve this question
List item
enter image description here
I created the uploadProduct route in product.routes.js and I called it in the index.js file.
product.routes.js:
const express= require("express");
const uploadProduct = require("../controllers/product.controller");
const ProductValidation = require("../middlewares/validation/product.validation");
const router = express.Router()
router.post("/uploadProduct",ProductValidation.addProduct,uploadProduct)
module.exports = router
index.js:
const router = require("express").Router()
const product = require("./product.routes")
router.use(product)
module.exports = router
and this is where the problems occur
product.validation.js:
const joi = require("joi");
const APIError = require("../../utils/errors");
const Response = require("../../utils/response");
class ProductValidation {
constructor() {}
static addProduct = async (req, res, next) => {
const schema = await joi.object({
ProductName: joi.string().required().max(45).min(1),
NumberOfProducts: joi.number().required().max(45).min(1),
UnitOfMeasurment: joi.string().required().max(45).min(1),
PurchasePrice: joi.number().required(),
SellingPrice: joi.number().required(),
QRcode: joi.string().required().max(45).min(1),
// İmage: joi.string().required().max(45).min(1),
});
try {
const value = await schema.validateAsync(req.body);
return new Response(value, "success").created(res);
} catch (error) {
if (error.details && error?.details[0].message)
throw new APIError(error.details[0].message, 400);
else throw new APIError("Please comply with validation rules", 400);
}
next();
};
}
module.exports = ProductValidation;
it is middleware for the uploadProduct route. And why can't use the next () function at the end of trycatch.
I can use the next() function before trying catch returns but I can't use this function end of try-catch. Why? Can trying to catch block returns affect the next codes? Because any code after try-catch in this file is unexpected code!
Thanks :)
Related
Can I call an imported function in app.get("/")? is it good practice?
Does this also mean that all logic must be done in the addArticle function?
post.js
const addArticle = async post => {
const postData = {
body: post.body,
title: post.title,
username: post.username
};
const { data } = await axios.post(
`${BASE_URL}/data/`,
postData
);
return data;
}
catch (err) {
console.log(err)
}
index.js
const express = require('express')
const axios = require('axios')
const postfunc = require (./post.js)
const app = express()
app.get("/", post.addArticle)
app.listen(3001)
It’s acceptable to pass your route handler however you see fit. However, your addArticle function doesn’t conform to express route handler signature.
Your function should handle two arguments, being express.Request and express.Response instances respectively.
Finally, note that returning a value from a route handler does nothing — if you want to send that value to the client, you’ll need to use res.send or similar method.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
try {
console.log('11111')
const {
data: { tasks },
} = await axios.get('/api/v1/tasks')
console.log('22222 ' + await axios.get('/api/v1/tasks') )
console.log('33333 ' + tasks)
Issue is: tasks is undefined
The problem was in Backend..
the route associated with await axios.get('/api/v1/tasks') i.e get('/api/v1/tasks') had this code
``` const getAllTasks = async (req,res) => {
try{
const tasks = await Task.find({})
res.status(200).json(tasks)
}
catch(error){
res.status(500).send({msg: error})
}
}```
instead above. It should be
```const getAllTasks = async (req,res) => {
try{
const tasks = await Task.find({})
res.status(200).json({ tasks })
}
catch(error){
res.status(500).send({msg: error})
}
}```
The change is in res.status(200).json({ tasks })
This question already has answers here:
meaning of module.exports= function in node.js
(2 answers)
What is the purpose of Node.js module.exports and how do you use it?
(13 answers)
Closed 1 year ago.
I have looked out for this question, but unable to find the reason for this. I just started working on a new project though I'm able to get the results using one of the ways, but why it is not working when we directly export it.
When I try to export an async function like this, I get an error saying that hash is not a function :
hashing.js
const bcrypt = require('bcrypt');
module.exports.hashing = async (password) => {
const salt = await bcrypt.genSalt(10);
const hashedResult = bcrypt.hashSync(password, salt);
console.log(hashedResult);
return hashedResult;
}
Importing hashing module to register module:
const dbConnection = require('../db/db');
const errorCodes = require('../db/error.code.json');
const hash = require('../controllers/shared/hashing');
module.exports.register = async (req, res) => {
try {
const db = await dbConnection();
const {email, username } = req.body;
const password = await hash(req.body.password); --> it says hash is not a function
const user = new db({email: email, password: password, username: username});
user.save((err, result) => {
if (err) {
res.send(errorCodes[err.code])
return;
}
res.status(201).json(result)
});
} catch (error) {
console.log(error);
}
}
But when I make these changes to the hashing.js, it works :
const bcrypt = require('bcrypt');
const hashing = async (password) => {
const salt = await bcrypt.genSalt(10);
const hashedResult = bcrypt.hashSync(password, salt);
console.log(hashedResult);
return hashedResult;
}
module.exports = hashing;
It says type error, I am attaching it to the question. Am I doing anything wrong? How can I get the function running?
Error Image:
It didn't matter that your function is asynchronous.
When you export a function like this:
module.exports.hashing = () => {
// ...
}
To use it properly, you have to do:
const {hashing} = require('../controllers/shared/hashing');
hashing();
// OR depending on your file context
const hash = require('../controllers/shared/hashing');
hash.hashing();
If you want to do:
const hash = require('../controllers/shared/hashing');
hash();
Export your function like this:
module.exports = () => {
// ...
}
I am a beginner and currently working my way through a node.js API authentication tutorial. All going well until having to refactor code into separate files and now I keep getting the following error "TypeError: schema.validate is not a function" when sending a JSON request via Postman, regardless if the request should fail the validation or not.
Here is my code for validation.js
//Validation
const Joi = require('#hapi/joi');
//Register Validation - wrap it in a function as there will be multiple schemas
const registerValidation = data => {
const schema = {
name: Joi.string().min(6).required(),
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
}
return Joi.assert(data, schema);
}
// Login Validation
const loginValidation = data => {
const schema = {
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
}
return Joi.assert(data, schema);
}
module.exports.registerValidation = registerValidation;
module.exports.loginValidation = loginValidation;
My auth.js code is like so
const router = require('express').Router();
const User = require('../model/User');
const { registerValidation } = require('../validation');
router.post('/register', async (req, res) => {
//Validate data before creating user
// const { error } = schema.validate(req.body);
const { error } = registerValidation(req.body);
if(error) return res.status(400).send(error.details[0].message);
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
date: req.body.date
});
try {
const savedUser = await user.save();
res.send(savedUser);
}catch(err){
res.status(400).send(err);
}
});
router.post('/login')
module.exports = router;
Can someone assist at all? The only thing I have changed is that I was using Joi.validate which is no longer valid according to the docs so I have updated it to Joi.assert.
Many thanks
Use the below approach for validation as joi.validate is no longer supported
const schema = Joi.object({
name: Joi.string().min(6).required(),
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
})
return schema.validate(data)
For anyone still getting "schema.validate is not a function":
When you declare the schema, make sure you declare Joi.object, like so:
const schema = Joi.object({
username: Joi.string().etc
})
Declare like this
const schema = Joi.object({username: Joi.string().etc })
This thing works!!
Normally you are declaring like this:-
const schema = {username: Joi.string().etc }
Instead of that declare like that
const schema = Joi.object({username: Joi.string().etc })
Note: In the above version of 17.0.0, there is no Joi.validate function so with above thing you have to use schema.validate(req.body)
It will work.
Can I use axios and mongoose to build an API? That's because I am new in the back-end developement, so I tried and I gotta an error like below, I was trying to do an API with axios and mongoose, but I don't know if i can use them together, I was kind to test this code to see if they work, but apparently not. So any suggestion to code better or is that correct what I am doing, is there other way ? I sure there is, but which recommendion you guys can make.
I want to create two separate files, one for controllers like "product.controller" and use my api to do all the requests that my differents controllers could need
Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
product.controller.js
const Product = require('../models/product.model');
const api = require('../api/api');
mongoose = require('mongoose').set('debug', true);
// To create a new Product
exports.create = async (req, res) => {
const product = await api.create('/product', req.body);
res.status(201).send({ message: 'The product has been created successfully !', product });
};
api.js
const axios = require('axios');
const baseURL = require('../config/database');
const list = async(key) =>{
const content = await axios.get(baseURL.local.urlDataBase + key +'.json')
if(content.data){
const objects = Object
.keys(content.data)
.map(key=>{
return{
id: key,
...content.data[key]
}
})
return objects
}
return []
}
const get = async(key, id) => {
const content = await axios.get(`${baseURL.local.urlDataBase}/${key}/${id}.json`)
return {
id: id,
...content.data
}
}
const create = async(key, data) =>{
await axios.post(`${baseURL.local.urlDataBase}/${key}.json`, data)
return true
}
module.exports = {
list, create
}