I have a complicated problem with my Node/React app. I have a shopping cart with the final element when checking out is to add order details to my MySQL database, however my function is returning an error from the controller. I am posting the relevant code, the full code is too extensive for a post.
This is the Node route:
module.exports = function(app) {
var controller = require('../controllers/controller');
// controller Routes
app.route('/products')
.get(controller.list_all_products)
.post(controller.create_a_product);
app.route('/products/:product_type')
.get(controller.products_by_type);
app.route('/product/:productId')
.get(controller.read_a_product)
.put(controller.update_a_product)
.delete(controller.delete_a_product);
};
This is the relevant part of the controller:
exports.create_a_product = function(req, res) {
var new_product = new Product(req.body);
//handles null error
if(!new_product.product || !new_product.status){
res.status(400).send({ error:true, message: 'Please provide product/status' });
} else {
Product.createProduct(new_product, function(err, product) {
if (err)
res.send(err);
res.json(product);
});
}
};
The relevant part of the Model:
var Product = function(product){
this.product = product.product;
this.status = Product.status;
this.created_at = new Date();
};
Product.createProduct = function (newProduct, result) {
sql.query("INSERT INTO orders set ?", newProduct, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
console.log(res.insertId);
result(null, res.insertId);
}
});
};
Then the React side uses this api call:
import $ from 'jquery'
export const addOrder = order => {
const urlString = "http://localhost:9000/products"
return $.ajax({
url: urlString,
method: "POST",
data: order,
success: () => {
console.log('order logged')
},
error: (status, err) => {
console.log(status)
}
})
}
And finally I make the call with this var:
var r = await addOrder(this.state.order).then(res => res.json())
The order details are a simple object:
this.state = {
order: {
oid: '',
order_date: '',
products: '',
first_name: '',
last_name: '',
email: '',
address: '',
city: '',
province: '',
zip: '',
country: ''
}
}
When executing I get the error 'Please provide product/status' from the controller.
I know this is a tough one, any help is hugely appreciated.
orderobject you send to theproductsendpoint neither does have astatusnor aproductproperty. Thus the error. Are you really supposed to send anorderobject to theproductsendpoint? Shouldn't this be anordersendpoint? Or aproductobject?