API testing using postman - javascript

I am developing Rest APIs for some project and testing them using postman to send the data on my mLab server. But All I could get:
{
"error": {
"message": "ENOENT: no such file or directory, open 'C:\\Users\\Admin\\Desktop\\periodical API\\uploads\\2018-06-16T14:34:38.384Zhd-wallpaper-of-live.jpg'"
}
}
Here's my route code:
const mongoose = require("mongoose");
const Product = require("../models/product");
exports.products_get_all = (req, res, next) =>
{
Product.find()
.select("name price quantity date subject _id productImage")
.exec()
.then(docs => {
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
quantity: doc.quantity,
date: doc.date,
subject: doc.subject,
productImage: doc.productImage,
_id: doc._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + doc._id
}
};
})
};
res.status(200).json(response);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_create_product = (req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
quantity: req.body.quantity,
date: req.body.date,
subject: req.body.subject,
productImage: req.file.path
});
product
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Created product successfully",
createdProduct: {
name: result.name,
price: result.price,
quantity: result.quantity,
date: result.date,
subject: result.subject,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_get_product = (req, res, next) => {
const id = req.params.productId;
Product.findById(id)
.select("name price quantity date subject _id productImage")
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json({
product: doc,
request: {
type: "GET",
url: "http://localhost:3000/products"
}
});
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.products_update_product = (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.update({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
message: "Product updated",
request: {
type: "GET",
url: "http://localhost:3000/products/" + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_delete = (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json({
message: "Product deleted",
request: {
type: "POST",
url: "http://localhost:3000/products",
body: { name: "String", price: "Number" }
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
I myself could not figure out the problem as I am a bit newbie on developing APIs.

On Linux servers ENOENT means
“No such file or directory”
said that the response you are getting is trying to let you know that,
The directory where you are trying to save, does not exist
The place of file you are looking for does not exist.
What I do recommend you is that you use your debugger tool to stop the execution before you try to get to the directory or where you try to read your file. That way you will understand where your code is failing.
Now many times when I get to this error, usually means that the directory does not exist but more frequently that you do no have permission to save the file.
Good luck, I hope it helps.
http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html

Related

How can i get list of customers between a date range?

How can i get list of customers between a date? There will be a starting date and an ending date picker in my frontend react app, but i dont know how to get the data in a specific date range uisng mongoose in my express app. Im posting my mongoose model and router code below, a little help will be appreciated --
mongoose model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const customerSchema = new Schema(
{
name: {
type: String,
required: true,
max: 50,
},
phone: {
type: String,
required: true,
max: 12,
},
address: {
type: String,
required: true,
max: 100,
},
pin: {
type: String,
required: true,
max: 6,
},
remarks: {
type: String,
max: 50,
},
isConverted: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
const Customer = mongoose.model(
'Customer',
customerSchema
);
module.exports = Customer;
route
const router = require('express').Router();
const Customer = require('../models/Customer');
router.post('/add', (req, res) => {
const newCustomer = new Customer({
name: req.body.name,
phone: req.body.phone,
address: req.body.address,
pin: req.body.pin,
});
newCustomer
.save()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error creating a new customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/list', (req, res) => {
Customer.find()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyphone/:phone', (req, res) => {
Customer.findOne({ phone: req.params.phone })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyname', (req, res) => {
Customer.findOne({ name: req.body.name })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.put('/:id', (req, res) => {
Customer.findByIdAndUpdate(req.params.id, {
remarks: req.body.remarks,
isConverted: req.body.isConverted,
})
.then((response) => {
res.send('Successfully updated');
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/:id', (req, res) => {
Customer.findById(req.params.id)
.then((cx) => {
res.send(cx);
})
.catch((err) => {
res.status(500).json(err);
});
});
module.exports = router;
add new route like this
router.post('/getByDate', (req, res) => {
Customer.find({ createAt:{$gt: req.body.min,$lt:req.body.max })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
and send data from front lime this
{
min:mindate,
max:maxdate
}

trying to get single item from list

I have a fairly bare bones mern stack and im trying to call getUsers and then retrieve a single user from the returned list of users.
however using [] doesnt seem to work. It looks like getUsers correctly returns the list of users but idk how to pull a single one out
user-ctrl.js
const User = require('../models/user-model')
createUser = (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a user',
})
}
const user = new User(body)
if (!user) {
return res.status(400).json({ success: false, error: err })
}
user
.save()
.then(() => {
return res.status(201).json({
success: true,
id: user._id,
message: 'User created!',
})
})
.catch(error => {
return res.status(400).json({
error,
message: 'User not created!',
})
})
}
updateUser = async (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a body to update',
})
}
User.findOne({ _id: req.params.id }, (err, user) => {
if (err) {
return res.status(404).json({
err,
message: 'User not found!',
})
}
user.name = body.name
user.email = body.email
user
.save()
.then(() => {
return res.status(200).json({
success: true,
id: user._id,
message: 'User updated!',
})
})
.catch(error => {
return res.status(404).json({
error,
message: 'User not updated!',
})
})
})
}
deleteUser = async (req, res) => {
await User.findOneAndDelete({ _id: req.params.id }, (err, user) => {
if (err) {
return res.status(400).json({ success: false, error: err })
}
if (!user) {
return res
.status(404)
.json({ success: false, error: `User not found` })
}
return res.status(200).json({ success: true, data: user })
}).catch(err => console.log(err))
}
getUserById = async (req, res) => {
await User.findOne({ _id: req.params.id }, (err, user) => {
if (err) {
return res.status(400).json({ success: false, error: err })
}
if (!user) {
return res
.status(404)
.json({ success: false, error: `User not found` })
}
return res.status(200).json({ success: true, data: user })
}).catch(err => console.log(err))
}
getUsers = async (req, res) => {
await User.find({}, (err, users) => {
if (err) {
return res.status(400).json({ success: false, error: err })
}
if (!users.length) {
return res
.status(404)
.json({ success: false, error: `User not found` })
}
return res.status(200).json({ success: true, data: users })
}).catch(err => console.log(err))
}
module.exports = {
createUser,
updateUser,
deleteUser,
getUsers,
getUserById,
}
You need to actually call the getUsers function (with parenthesis), and then wait for the promise to resolve, with await
var allUsers = await UserCtrl.getUsers();
var defaultUser = allUsers[0];
or
UserCtl.getUsers()
.then(u=>u[0])
.then(user=>{
// insert code that uses the user here
})
It's a promise, so try with async/await
var allUsers = await UserCtrl.getUsers();
var defaultUser = allUsers[0];
To make await work, put async infront of your method:
async createUser = (req, res) => {

Sequelize update information

I've been struggling with this issue for a day now and can't seem to figure out a way to resolve it. This is the code I'm running
Client side:
const nameInput = document.querySelector("#nameInput");
const urlInput = document.querySelector("#urlInput");
const rowAlert = document.querySelector(".alertAppend");
const divAlert = document.createElement("div");
const nameUpdate = async (e) => {
e.preventDefault();
fetch("/auth/updateName", {
method: 'POST',
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify({
name: nameInput,
url: urlInput,
})
})
.then(function (data) {
console.log('Request success: ', data);
})
.catch(function (error) {
console.log('Request failure: ', error);
});
};
submitName.addEventListener("click", nameUpdate);
API:
router.get("/updateName", auth, async (req, res) =>{
try {
const { name, url } = req.body;
const ime = name;
const uid = req.session.passport.user;
db.User.find({ where: { id: uid } })
.on('success', function (user) {
if (user) {
user.update({
name: ime,
webhook: url
})
.success(function () {})
}
})
res.json({ message: url});
} catch (err) {
if (err) res.status(500).json({ message: "Internal Error"})
}
});
For some reason it just runs the select query and never proceeds to update the user.
Chrome console output
Debug console output
Sequelize model in case it helps:
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
name: {
type: DataTypes.STRING
}
})
return User;
}
The issue was in the API, it's supposed to be router.post
router.post("/updateName", auth, async (req, res) =>{
const { ime, url } = req.body;
const uid = req.session.passport.user;
console.log(ime);
db.User.findOne({where: {id: uid}})
.then(record => {
let values = {
name: ime,
webhook: url
}
record.update(values).then( updatedRecord => {
console.log(`updated record ${JSON.stringify(updatedRecord,null,2)}`)
res.status(200).json({ message: "success"});
})
}
})
.catch((error) => {
// do seomthing with the error
throw new Error(error)
})
});
You can try the following code
await db.User.update({
name: ime,
webhook: url
}, { where: { id: uid } });
When defining your model I don't see the webhook field

Why is my REQ.body.imageURL undefined in PUT method?

I'm trying to write the back-end for a foodie review app. The problem I'm having is at the PUT method, when I'm trying to modify a certain post, the req.body does not contain the imageUrl if I do not modify the URL . When req.file exists (the image), then everything works, because I set up a new imageURL. For some reasons I get the userId, description and everything else back except the imageUrl.
Here is my code:
exports.modifySauce = (req, res, next) => {
let sauce = new Sauce({ _id: req.params._id });
if (req.file) {
const url = req.protocol + '://' + req.get('host');
req.body.sauce = JSON.parse(req.body.sauce);
sauce = {
_id: req.params.id,
name: req.body.sauce.name,
manufacturer:req.body.sauce.manufacturer,
mainPepper:req.body.sauce.mainPepper,
description: req.body.sauce.description,
imageUrl: url + '/images/' + req.file.filename,
heat: req.body.sauce.heat,
userId: req.body.sauce.userId
};
} else {
sauce = {
_id: req.params.id,
name: req.body.name,
manufacturer:req.body.manufacturer,
mainPepper:req.body.mainPepper,
description: req.body.description,
imageUrl: req.body.imageUrl,
heat: req.body.heat,
userId: req.body.userId
};
}
Sauce.updateOne({_id: req.params.id}, sauce).then(
() => {
res.status(201).json({
message: 'Sauce updated successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
More information, in my Repo.
And here is the front end repo.
https://github.com/OpenClassrooms-Student-Center/nem-stack-hot-takes

Api calls MEAN4+

So i'm working in a mean stack application but i just don't get my api right..
The only thing that works is the GET !
My post and put doesn't seems to work, I think i got my syntax wrong but I just don't find the right one on the internet.
//GET
router.get('/employees', (req, res) => {
connection((db) => {
db.collection('employees')
.find()
.toArray()
.then((employees) => {
response.data = employees;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
// POST
router.post('/employees', (req, res) => {
const employees = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
db.collection('employees').insert(employees, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
//PUT
router.put('/employees/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const employee = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
db.collection('employees').update(details, employee, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(employee);
}
});
});
your PUT and POST methods dont have connections to the database established so db.collection is undefined in both
router.post('/employees', (req, res) => {
const employees = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
connection((db) => {
db.collection('employees').insert(employees, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
});
//PUT
router.put('/employees/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const employee = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
connection((db) => {
db.collection('employees').update(details, employee, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(employee);
}
});
});
});

Categories

Resources