Express server stops without throwing error - angularjs

I am using the angular fullstack generator, but I do not believe this is the problem. I am working with Stripe.js and trying to save the data to the SQLite database using Sequelize. I have tried many different things, but the server stops running when it gets to the part where it is supposed to save the data.
app.post('/register', auth.isAuthenticated(), function(req,res){
console.log('access: ',req.query)
var userId = req.body._id
var data = req.body.data
//create stripe acct for artists
stripe.accounts.create(data, function(err,acct){
if(err){
console.log('err!!! ', err)
} else {
console.log('acct: ', acct)
//look for user in database
db.User.find({
where: {
_id: userId
}
})
.then(function(user) {
if(user){
console.log('user: ', user)
//add stripe acct info to db
console.log('acct:', user.dataValues.account);
/*this is where the Server stops running*/
user.updateAttributes({
account: JSON.stringify(acct)
}).success(function(){
console.log('newacct:', user.dataValues.account);
//just to see if it works
res.send({'account': acct});
})
} else {
console.log('no user found bruh')
}
});
}
})
})
I have tried redirecting, changing req.method to 'get' and then res.redirect. res.end() all of the above, but it always stops running. No errors are thrown it just simply says 'Stopping Express Server'. Thanks in advance for the help!

Related

AWS JS SDK: How do I access GameLift data from a subaccount / another role using the root IAM account?

I'm not too familiar with the terms, so please bear with me.
I'm working on a CMS site using react. We've already got logon via AWS Cognito in place, and we used to have a page that displays GameFleet data.
However, the Aliases and Fleets have been moved to a subaccount:
And as such the GameFleet page is empty.
I've initially overcome this problem by creating an IdentityPool (and roles) for the DevRole subaccount, as the CMS retrieves the GameFleet data via the following code:
componentDidMount() {
AWS.config.region = REGION;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: IDENTITY_POOL_ID // <--- Changed this to new IdentityPoolId
});
AWS.config.credentials.get(function(err) {
if (err) console.log(err);
else console.log(AWS.config.credentials);
});
await this.requestGameLiftData();
};
requestGameLiftData = async () => {
const gamelift = new AWS.GameLift();
try {
const aliasData = await new Promise((resolve, reject) => {
gamelift.listAliases({}, function(err, data) {
if (err) { reject("Aliases failed");}
else { resolve(data); }
});
});
} catch (error) {
console.log(error);
}
};
But the problem now is that there is a new subaccount, one I don't have access to, and I can foresee that new subaccounts might be created which won't have the necessary IdentityPoolId required for my approach.
I've been told accessing the subaccount GameLift data from the root account should be possible, but I'm not sure how. I've been looking at the IAM page under the main account, but there doesn't seem to be anything there that could point to the subaccounts.
Am I missing anything?
You need to use AWS Assume roles functionality here using which your primary account can assume role of secondary account and get temporary credentials of sub-account which can be used to pull the data from sub-account from primary account.
https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html

How to get return value from Mongoose save function using axios in React JS?

I am new to React JS and I created a simple application which accept UserName and Email and inserts to MongoDB.
I use React + Node + Express + Mongoose + MongoDB and I was able to insert the record successfully
DB.js
router.route("/insert").post(function(req, res) {
let comments = new Comments(req.body);
console.log(req.body)
comments.save();
});
App.js
axios.post("http://localhost:4000/insert", {
UserName: username,
UserEmail: email,
Comments: comments
})
Now, I want to return 'numRowsAffected' from DB.js to App.js.
Hence, I modified DB.js by adding callback to mongoose save() function
router.route("/insert").post(function(req, res) {
let comments = new Comments(req.body);
console.log(req.body)
comments.save(function(err, comments, numRows) {
if ( err ) {
res.send(err);
}
else {
res.json({ message: 'Comments added', data: numRows });
}
});
});
However, I don't know how to change the code on App.js (ie in axios.post) to fetch the return value from DB.js
Any help is highly appreciated
You can use Mongoose.update() with upsert option set to true instead of Mongoose.save() and read the nModified and nInserted property of update return value.
You can see this post for more detail.

Fetch status 200 but pending endllessly, except first call

I've been searching to solve this problem for a while but couldn't find a working solution.
I'm making a simple social network website and this API returns a article data such as text, image and video url, etc, all saved in server's local MySQL Database. My front-end is React and server is Nginx reverse proxy with Node.js using Express. When I load the page, I create 5 React components that each make fetch request for given article number.
The following code snippet is the fetch API that asks the server to fetch data from database:
//server-side script
app.get('/api/getArticle/:id', (req, res) => {
const con = mysql.createConnection({
host: 'myhost_name',
user: 'myUser',
password: 'myPassword',
database: 'myDB',
});
con.connect(function (err) {
if (err) {
throw err;
}
console.log("Connected!");
})
const idInterest = req.params.id.toString();
console.log(idInterest)
let sql = 'some_sql';
con.query(sql, function (err, result) {
if (err) {
res.status(500).send("Error while getting article data");
return;
}
else {
res.set('Connection', 'close')
res.status(200).send(result);
console.log("ended")
con.end();
return;
}
})
}
//React script
//index.js
fetch('http://mywebsite.com/api/getMaxArticleId/')//Retrieve top 5 article ID
.then((response) => {
for (let i = 0; i < data.length; i++) {
nodesList.push(<Container articleId={data[i]['id']}/>)
}
ReactDOM.render(<React.StrictMode><NavBar />{nodesList}<Writer writer="tempWriter" /></React.StrictMode>, document.getElementById('root'));
})
//Container.jsx; componentDidMount
const url = "http://mywebsite.com/api/getArticle/" + this.props.articleId.toString();
fetch(url, {
method: 'GET',
credentials: "include",
}).then((response) => {
response.json().then((json) => {
console.log(json);
//processing json data
This used to work very fine, but suddenly the getArticle/:id calls started to show 200 status but 'pending' in 'time' column in Chrome network tab, endlessly, all except the first*getArticle/:idcall. This prevents my subsequent .then() in each Container from being called and thus my entire tab is frozen.
Link to image of network tab
As you see from the image, all pending fetches are missing 'Content Download' and stuck in 'Waiting(TTFB)', except the first call, which was '39'
I checked the API is working fine, both on Postman and Chrome, the server sends result from DB query as expected, and first call's Json response is intact. I also see that console.log(response.json()) in React front-end shows Promise{<pending>} with *[[PromiseStatus]]: "Resolved"* and *[[PromiseValue]]* of Array(1) which has expected json data inside.
See Image
This became problematic after I added YouTube upload functionality with Google Cloud Platform API into my server-side script, so that looks little suspicious, but I have no certain clue. I'm also guessing maybe this could be problem of my React code, probably index.js, but I have no idea which specific part got me so wrong.
I've been working on this for a few days, and maybe I need common intelligence to solve this (or I made a silly mistake XD). So, any advices are welcomed :)

Node.js mssql close open connection

I am building an API integration application in Node.js using the "mssql" package. I have the data pulling from the third-party API, and stored in my SQL Server. However, my DB connection stays open forever and keeps my app running. Everything that I have tried ends the connection before the data can be stored. So, I can either store my data and keep the connection open forever, or end my connection and not store the data. The best that I have found is something like this answer: https://stackoverflow.com/a/45681751/5552707.
And I have tried that in my app, which still kills my connection before data is stored:
sql.connect(sqlConfig).then(pool => {
var request = new sql.Request(pool);
var result = request.bulk(table, (err, result) => {
if(err){
console.log("fail. " + err);
return;
}
})
}).catch(err => {
console.log('There was an error processing the request. ' + err);
}).then(() => {
console.log('done');
process.exit(1);
});
They docs don't explain how to do this, which is frustrating.
Any ideas would be awesome!
Thanks!
Adding
process.exit();
to the callback function did the trick.
var request = new sql.Request(pool);
var result = request.bulk(table, (err) => {
if(err){
console.log("fail. " + err);
return;
}
process.exit(1);
})

kinvey fetching and remove not working (AngularJS)

I have this problem with kinvey backend,
I'm trying to fetch data from my collection but it doesn't work for me. here is my code :
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
Can you help me please
If you let run the code you have posted then consider four things:
Make sure you have Kinvey implemented:
<script src="https://da189i1jfloii.cloudfront.net/js/kinvey-html5-sdk-3.10.2.min.js"></script>
Make sure you have initialized the Kinvey service before:
// Values shown in your Kinvey console
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
Make sure you are logged in with a user that has the rights to read your collection (should be fine using the All Users role (default)):
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
})
.catch(function(error) {
console.log (error);
});
Output the return result to see whats coming back. To make sure you do the query AFTER successful login, paste you query inside the .then function of login.
I'm not sure if your query is valid unter 3.x since a lot has changed and I'm not working with older Kinvey versions.
So that all together would look like this:
// Initialize Kinvey
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
// Login with already registered user
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
// Your query
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// Output of returning result
console.log (entity);
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
})
.catch(function(error) {
console.log (error);
});
There are now three return sets possible:
Nothing (as you say) -> Something missing/wrong in the code (compare yours with mine)
Empty array: Your query didn't find anything, adapt the search value(s)
One or more entries in the array -> All fine, what you were looking for!
Hope that helps!
When querying by _id there is a built in method: http://devcenter.kinvey.com/angular/guides/datastore#FetchingbyId
Try switching to var stream = dataStore.findById('entity-id');
Also check to make sure you don't have any preFetch or postFetch BL that is interfering with the query.

Resources