I have always used mongoose in my applications, however I am using sequelize in a specific application.
however I am facing problems with caching on the client side.
for example, in my list of categories, there is the function of editing, when I edit and save, the client side application calls the listing again, to show the updated data.
this works very well with mongoose, but with sequelize the cache does not let the data be updated on screen.
I leave below an example of how I am doing the listing and editing on the server side
const get = (req, res, next) => {
categoriesModel.findAll({})
.then(data => res.json({
status: true,
data: data
}))
.catch(error => res.json({
status: false,
data: [],
msg: error
}))
}
const put = (req, res, next) => {
categoriesModel.update({
title: req.body.title,
active: req.body.active
},
{
where: {
id: req.params.id
}
})
.then(data => res.json({
status: true,
data: data,
msg: 'Success!'
}))
.catch(error => res.json({
status: false,
data: [],
msg: error
}))
}
I solved my problem by adding the following header rules
app.use(function(req, res, next) {
res.set("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0")
res.set("Pragma", "no-cache")
res.set("Expires", 0)
next()
})
Related
router.get("/stocks/symbols/:industry", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.where("industry", "like", '%h%')
.then((rows) => {
res.json({ Error: false, Message: "Success", Cities: rows })
})
.catch((err) => {
console.log(err)
res.json({ Error: true, Message: "Error in MySQL query" })
})
})
Above is the code for getting stocks with industry that includes h in it.
Such as Healt'h' Care and Information Tec'h'nology
What I'm trying to do is instead of using '%h%' to get the fixed response, use req.params.industry
What do i have to do to fix it?
router.get("/stocks/symbols", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.modify(function(queryBuilder) {
if (req.query.param) {
queryBuilder.where('industry',req.query.param);
}
})
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.then((rows) => {
res.json(rows)
})
.catch((err) => {
console.log(err)
res.json({ Error: false, Message: "Error in MySQL query" })
})
})
I'm trying to make such a functionality to use querystring.
At the moment this runs without error but doesn't do anything.
Whether I put ?industry=h or anything after the route, it returns the same data.
There was an example I followed, but for some reason its not working.
What else am i missing?
router.get("/stocks/symbols/:industry", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.where("industry", "like", `%${req.params.industry}%`)
.then((rows) => {
res.json({ Error: false, Message: "Success", Cities: rows })
})
.catch((err) => {
console.log(err)
res.json({ Error: true, Message: "Error in MySQL query" })
})
})
This does similar job that i want to do but it doesn't use the querystring.
You need to apply the correct query parameter - in your code you use query.param meaning that your url would need to contain /stocks/symbols?param=tbd
If you're expecting industry as a query-param, you need to change it to:
.modify(function(queryBuilder) {
if (req.query.industry) {
queryBuilder.where('industry',req.query.industry);
}
})
when I send a fetch request for JSON data, it returns the response object, but not the data itself.
Can't figure out why
I've tried added headers, stringifying the data
My Express server
const productData = require('./storeProducts.json');
app.use(cors());
app.get('/products', (req, res) => {
res.json(JSON.stringify(productData));
});
app.listen(PORT, () => console.log(`Now listening on ${PORT}`));
my fetch request
const fetchProducts = async () => {
const data = await fetch('http://localhost:3001/products');
console.log(data)
};
when I console.log the data i am receiving, instead of the JSON object, im getting
Response {type: "cors", url: "http://localhost:3001/products", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3001/products"
proto: Response
any help would be appreciated
You need to do something like:
const fetchProducts = async () => {
let data = [];
await fetch('http://localhost:3001/products')
.then(res => res.json())
.then(response => {data = response;})
console.log(data)
};
When you use fetch, it returns an object and res.json() method extracts the JSON data from that object and returns a promise, that promise can be used to perform our operations on the result. e.g mapping data on a table, making graphs, chart, authentication etc.
Hope this solves your problem.
I'm unable to understand what actually is wrong with my code. But I know there is a problem in how I'm implementing Promise. As Shipment.findAll() returns a Promise, and I'm creating a promise again for my router to consume.
Then why createShipment is working fine, and getAllShipments is not working.
Controller for Shipment
const Worker = require ('../models').Worker;
const Shipment = require ('../models').Shipment;
function createShipment (shipmentName, shipmentStatus) {
return new Promise ((resolve, reject) => {
Shipment.create({name: shipmentName, status: shipmentStatus})
.then (shipment => resolve(shipment))
.catch (error => reject(error));
});
}
function getAllShipments () {
return new Promise ((resolve, reject) => {
Shipment.findAll()
.then(allShipments => {
console.log(allShipments);
return resolve(allShipments);
})
.catch(error => reject(error))
})
}
module.exports = {
createShipment,
getAllShipments
}
Shipment Router
var router = require('express').Router();
var Shipment = require('./../../../controllers/shipment');
router.post ('/' , (req,res) => {
Shipment.createShipment ('New Shipment', 'Pending')
.then (shipment => {
res.status(200).json({status: true, data: shipment, errors: null, msg: "Shipment Added Successfully"});
})
.catch (error => {
res.status(200).json({status: false, data: {}, errors: error, msg: "Error Creating Shipment. Please see details in Errors Object"});
});
});
router.get('/' , (req, res) => {
Shipment.getAllShipments()
.then(allShipments => {
return res.status(200).status({status: true, data: allShipments, errors: null, msg: "All Shipments fetched successfully"});
})
.catch(error => {
return res.status(200).json({status: false, data: {}, errors: error, msg: "Error Fetching Shipments. Please see details in Errors Object"});
});
})
module.exports = router;
What I'm doing wrong ? Because getAllShipments is giving my output on console but route is not sending response and just waiting and waiting.
Change :
Shipment.getAllShipments()
.then(allShipments => {
return res.status(200).status({status: true, data: allShipments, errors: null, msg: "All Shipments fetched successfully"});
})
to:
return res.status(200).json({status: true, data: allShipments, errors: null, msg: "All Shipments fetched successfully"});
Just a typo and you wrote down a status two times instead of json
I want to get data from form and based on that, add data to three tables in mySQL, I use Sequelize to do so, However I don't how to do so, my current idea gives error:
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers
after they are sent to the client
My code is like this:
app.post("/device/add", (req, res) => {
db.Devices.create({
device_id: req.body.device_id,
server: req.body.server,
type: req.body.type
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
db.Modules.create({
device_id: req.body.device_id,
device_options: req.body.device_options,,
sleep_options: req.body.sleep_options
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
db.Tests.create({
device_id: req.body.device_id,
gsm_tests: req.body.gsm_tests,
led_tests: req.body.led_tests,
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
});
can I somehow create it in one response? Or how to make it work
The problem is that you are trying to send again a response after you have sent one.
For more clarification, refer here
You can use Promise.all() to accumulate the results and then send it in one res.json() call.
const createDevice = db.Devices.create({
device_id: req.body.device_id,
server: req.body.server,
type: req.body.type
})
const createModules = db.Modules.create({
device_id: req.body.device_id,
device_options: req.body.device_options,
sleep_options: req.body.sleep_options
})
const createTests = db.Tests.create({
device_id: req.body.device_id,
gsm_tests: req.body.gsm_tests,
led_tests: req.body.led_tests,
})
Promise
.all([createDevice , createModules , createTests ])
.then(result=> {
res.json({
devices: result[0],
modules: result[1],
test : result[2]
});
})
.catch(err => {
throw(err);
});