I’m a very new geek trying to build an application using NodeJs and ExpressJs. I’m testing the backend with postman. some of the requests work perfectly but others don’t, I’ve been getting cannot get the url message, 404 not found for hours now, and as I mentioned other routes work very good.
Everything seems ok Server side, type content is JSON, I’ve checked the code multiple times and I can’t see the error. any ideas please? Thank you 🙏.
The server:
Postman response:
The model:
module.exports = (_db) => {
db = _db;
return SearchModel;
};
class SearchModel {
//Get a product by name
static getProductByName(productName) {
return db
.query('SELECT * FROM Products WHERE productName = ?', [
productName
])
.then((res) => {
console.log(res);
return res;
})
.catch((error) => {
console.log(error);
return error;
});
}
// Get products by gender
static getProductByGender(gender) {
return db
.query('SELECT * FROM Products WHERE gender = ?', [gender])
.then((res) => {
return res;
})
.catch((error) => {
return error;
});
}
// Get products by brand
static getProductByBrand(brand) {
return db
.query('SELECT * FROM Products WHERE brand=?', [brand])
.then((res) => {
return res;
})
.catch((error) => {
return error;
});
}
// Get products by mouvement
static getProductByMouvement(mouvement) {
return db
.query('SELECT * FROM Products WHERE mouvement=?', [mouvement])
.then((res) => {
return res;
})
.catch((error) => {
return error;
});
}
}
The route:
// Get a product by name
module.exports = (app, db) => {
const searchModel = require('../models/SearchModel')(db);
// Route pour afficher un produit par son nom
app.get('/api/v1/Search/name', async (req, res) => {
const productByName = await searchModel.getProductByName(
req.body.productName,
);
if (productByName.code) {
res.json({ status: 500, msg: 'Server Error!' });
} else if (!productByName) {
res.json({ status: 404, msg: 'Product not found!' });
} else {
res.json({ status: 200, result: productByName, msg: 'Voilà!' });
}
});
};
2
Answers
Are you sure that in GET request params are in
body
?This is the correct way:
And since the product is not found, you return
404
which means page not found as far as PostMan shows.req.body
inGET
andDELETE
request is not valid, you should use params or queries instead. Like: