I am working with Angular, Node and MySQL. I have a simple crud app in which I am adding,updating some data. Whenever I am adding/updating any data I want it to reflect changes in list grid as well.
I am using popups for add/update. So after adding or updating I am calling my generic function which gives me list of data but I was getting response 304 and changes not displayed in grid. So to overcome 304 I have use app.disable('etag') in Node.js which gives me status 200. But still changes not displayed, but when I refresh page manually I can see the changes.
Also when I am checking data in network just after performing operation it also holds old values.
Node.js
app.post("/addcity", function(req, res) {
d = req.body;
var con = mysql.createConnection(connectionString);
con.connect(function(err) {
if (err)
throw err;
var sql = "INSERT INTO tbl_city(city_name,state_id) VALUES('" + d.city_name + "'," + d.state_id + ")";
console.log(sql);
con.query(sql, function(err, result) {
if (err)
throw err;
res.send(result);
})
})
})
Angular code
PostData(addNewForm: NgForm) {
var object = {
"city_name": addNewForm.value.city_name,
"state_id": addNewForm.value.state_id
}
this.service.addCity(object).subscribe();
this.modalRef.hide();
this.getAllCities(); // this still gives old values even new City is added in database
}
Update
getCities() : Observable<any[]>{
var details = this.http.get(`${this.apiUrl}/cities`);
return forkJoin([details]);
}
You are calling the two requests in async, that's why by the time the city is added in database. this.getAllCities() gets the list of old cities try it like this.
PostData(addNewForm: NgForm) {
var object = {
"city_name": addNewForm.value.city_name,
"state_id": addNewForm.value.state_id
}
this.service.addCity(object).subscribe(
(data)=> {
this.modalRef.hide();
this.getAllCities();
}
);
}
Related
here is node.js code
var _num;
app.post("/api/get", (req, res) => {
_num = req.body.passNum;
console.log(_num + "insert");
callDb();
});
var callDb = () => {
app.get
("/api/get", (req, res) => {
var sqlSelect = "SELECT * FROM day" + _num;
console.log(_num + "outcome");
db.query(sqlSelect, (err, result) => {
res.send(result);
});
});
};
What is this code? : this code get a number from frontend(react) by click url (from day1 to day3) and it passes into var _num inside backend.
and function callDb gets the var _num, and add in to mysql query, so in conclusion, callDb calls different table from mysql(from day1 to day3).
what is problem? : The first few times work normally, and when clicked several times it doesn't work normally. as you see in my code, to check whether it is working properly, I added console.log (insert and outcome). as callDb inside app.post, after _num gets number from react, callDb has to be start.
so the sequence is, click day1 url->_num gets value"1" and console.log insert comes out(1 insert)->callDb SELECT day1 and console.log outcome comes out (1 outcome).
and after repeat click and go back to main page, the log is
1insert
1outcome
2insert
2outcome
3insert
3outcome
1insert
1outcome
2insert
2outcome
3insert
so from the six time, it makes problem. Only appears insert and after click, there is no log change. which means SELECT did not worked. and after refresh page, consolelog outcome gives proper outcome. so every 6click, user requires refresh.
I'm really confused because it works several times, and at some point it brakes. what is the problem and how can I fix?
app.post("/api/get", (req, res) => {
if(req.body.passNum){//first check if the required parameter is provided
_num = req.body.passNum; //get the parameter. You need to use 'escape string' to escape other dangerous characters which may lead to sql imjection.
db.query("SELECT * FROM day" + _num, (err, result) => {
if (err) {
console.log(err);
res.end("An error occcured while reading from the database");
} else {
res.send(result);
}
});
}else{
res.end("required fields are not provided");
}
});
I'm trying to create an app using Loopback (V3) and i've encountered a weird error.
I'm trying to create my Mysql tables using autoupdate(), but for my custom models it is not working.
This is what i've tried so far ->
var server = require('../server');
var ds = server.dataSources.db;
var models = ['test','Post','User', 'AccessToken', 'ACL', 'RoleMapping', 'Role'];
ds.isActual(models, function(err, actual) {
if (!actual) {
ds.autoupdate(null, function(err,result){
console.log("DONE!");
console.log(result);
});
};
});
The script works. If the database is empty it will create tables for all EXCEPT test and Post. Those are my custom models, the others are built into loopback.
Is it because of model type? (tried Model and PersistedModel) or is it something else? I even tried without the isActual check and still nothing.
I would recommend that you keep two separate arrays for built-in models and custom models and write code like following, that way you could know where the issue is. also, I think there is an error in your code near ds.autoupdate(null, fun.....
please follow according to the below code
var builtInModels = ['AccessToken', 'ACL', 'RoleMapping','Role'];
var userDefinedModels = ['Post','test'];
// migrate built-in models
dataSource.isActual(builtInModels, function (err, actual) {
if (!actual) {
dataSource.autoupdate(builtInModels, function (err, result) {
if(err) console.log(err);
console.log('Datasource Synced: Built in models');
});
}
});
// migrate userdefined models
dataSource.isActual(userDefinedModels, function (err, actual) {
if (!actual) {
dataSource.autoupdate(userDefinedModels, function (err, result) {
if (err) console.log(err);
console.log('Datasource Synced: User defined models');
});
}
});
I have this program which gets an entry from a database. It then changes some of the fields in this object and then sends it back with a PUT using Axios. My problem is that I don't know what to write in the PUT-function on the server side. When I try to do a PUT-request that only console.log the values I get the error:
"PayloadTooLargeError: Request entity too large".
selectedRoute contains the ID of the object to be sent back. chosenRoute contains the object.
Client-side:
onUpload(): void {
console.log(this.chosenRoute);
this.chosenRoute.name = this.routeName;
this.chosenRoute.text.paragraphs[0] = this.routeDescription;
this.chosenRoute.text.preamble;
if(this.activity != "") this.chosenRoute.activity = this.activity;
axios.put('http://localhost:8080/editRoute/' + this.selectedRoute, this.chosenRoute, {
onUploadProgress: uploadEvent => {
console.log('Upload Progress ' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " % ");
}
}).then(
res => {
console.log(res);
});
}
Server-side:
app.put('/editRoute/:id', function(req,res){
console.log(req);
console.log(res);
});
I have a an exports function I'm calling that should return a json array of draft results. In the route below in app.js, when I console.log draft_results, I get undefined
app.get('/draft-results', function(req, res) {
var draft_results = fantasy.getDraftResults(req, res);
console.log(util.inspect(draft_results, false, null));
//looks in views folder by default
res.render('draft-results', {
draft_results: draft_results
});
});
In my other file, this is the function that should be returning the json array. If i console.log draft, the data is there.
exports.getDraftResults = function(req, res, cb) {
oauth.get(
"http://fantasysports.yahooapis.com/fantasy/v2/league/" + conf.LEAGUE_ID + "/draftresults?format=json",
req.user.accessToken,
req.user.tokenSecret,
function(e, data, resp) {
if (e) console.error(e);
data = JSON.parse(data);
var draft = data.fantasy_content.league[1].draft_results;
res.json(draft);
}
);
};
I feel like I am returning the data incorrectly, and I can't seem to find any other good examples out there. Could someone please assist?
getDraftResults() is asynchronous. That means the results it generates occur sometime later. Thus, it cannot return its results directly from the function like you are trying to use.
It is unclear what you want to be doing here. Inside of getDraftResults() you are creating a JSON response back to the web request that started all this. That, in itself would be fine and will work as you have it (except the error handling is missing).
But, in your app.get() handler, you have completely different code that seems to thing that getDraftResults() is going to return a value (it has no return value at all) and then you will later use that return value.
So, if you just want getDraftResults to make a JSON response to the original web request, it's already doing that and you can remove the rest of what you have in the app.get() handler. If that's not really what you want to do and you want to use the response from getDraftResults() inside of the app.get() handler, then you will have to change the design of both functions and likely pass a callback to getDraftResults() so the callback can supply the asynchronous response and you can then continue the rest of the app.get() functionality in that callback.
If you're trying to do the latter, then here's a scaffolding (I don't know exactly what you're trying to accomplish so I can't be too detailed here):
app.get('/draft-results', function(req, res) {
fantasy.getDraftResults(req, function(err, draft_results) {
if (err) {
// send some sort of error response here
console.error(err);
return;
}
console.log(util.inspect(draft_results, false, null));
//looks in views folder by default
res.render('draft-results', {
draft_results: draft_results
});
});
});
exports.getDraftResults = function(req, cb) {
oauth.get(
"http://fantasysports.yahooapis.com/fantasy/v2/league/" + conf.LEAGUE_ID + "/draftresults?format=json",
req.user.accessToken,
req.user.tokenSecret,
function(e, data, resp) {
if (e) {
console.error(e);
cb(e);
return;
}
data = JSON.parse(data);
var draft = data.fantasy_content.league[1].draft_results;
// send results back to caller
cb(null, draft);
}
);
};
So I'm selecting Activities from the mongodb and populating User for each.
var query = Activity.find(query).populate("user");
return query.sort({created:"desc"}).exec(function(err, activities) {
debugger;
if (!err) {
return res.json(activities);
} else {
res.status(400).json(err);
}
});
As you can see I have a debugger; breakpoint is there, When I'm pring activities it prints an array of activities with the user object populated.
Also when I'm calling something like activities[0].toJSON() I get everything good!
But the response comes back with the user property empty !
I looked into the source of express.response.json(OBJ) and saw this line:
var body = JSON.stringify(val, replacer, spaces);
val is my activities
When calling JSON.stringify(activities) it will create a json with an empty user field.. any suggestions ?
Try the lean option. That gives back plain JS objects with no mongoose weirdness. Also, your error handling seems a little awkward, can be simplified.
var query = Activity.find(query).populate("user");
query.sort({created:"desc"}).lean().exec(function(err, activities) {
if (err) return res.status(400).json(err);
res.json(activities);
});
I would go even further, not hard-coding error sending in routes but simply passing along via if (err) return next(err) to error-handling middleware defined elsewhere in your app. You can still set the status, then use detection in your middleware, something like this:
app.use(function(err, req, res, next){
err.status = err.status || 500;
res.status(err.status).json(err);
});