CORS ISSUES INCONSISTENT - 2 Examples (VueJS and NodeJs) - node.js

I have the following axis post request
EXAMPLE 1
Front End
let data = this.itemsDuplicated;
console.log("length",data.length)
await axios({
method: "post",
url: `${url}/upDateTasksFromProgress`,
data: data
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log(e);
});
Node
router.post("/upDateTasksFromProgress", (req, res) => {
let mysql = "";
req.body.forEach(el => {
mysql = `${mysql} update tasks set startDate = '${el.startDate}', endDate = '${el.endDate}', duration = ${el.duration} where id = ${el.id};`
});
console.log(mysql)
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
resizeBy.send("Error with connection");
}
connection.query(mysql, function (error, result) {
if (error) {
console.log(error);
} else {
console.log(result)
res.json(result);
}
});
connection.release();
});
});
This works fine.
I also have:
EXAMPLE 2
Front End
let data = [];
this.tasks.forEach(el => {
let insert = {
id: el.id,
startDate: el.startDate,
endDate: el.endDate,
duration: el.duration,
parentId: el.parentId,
dependantOn: el.dependantOn,
fix: el.fix
};
data.push(insert);
});
console.log(data.length)
await axios({
method: "post",
url: `${url}/postTaskUpdates`,
data: data
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
Back End
router.post("/postTaskUpdates", (req, res) => {
let mysql = "";
req.body.forEach(el => {
mysql = `${mysql} update tasks set startDate = '${el.startDate}', endDate = '${el.endDate}', duration = ${el.duration}, parentId = '${el.parentId}', dependantOn = '${el.dependantOn}' where id = ${el.id};`
});
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
resizeBy.send("Error with connection");
}
connection.query(mysql, function (error, result) {
if (error) {
console.log(error);
res.json(error)
} else {
console.log(result)
res.json(result);
}
});
connection.release();
});
});
The second example gives me the following error:
“Access to XMLHttpRequest at
'https://www.testing-be.co.za/postTaskUpdates' from origin
'https://www.testing-fe.co.za' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.”
Both are in the exact same Route File on the backend.
The only difference is the number of records.
In the first example there are 22 records.
In the second there are about 1300 records.
Besides the number of records, all else is as shown above and to my mind exactly the same.
Any suggestions would be greatly appreciated.

Related

React - delete request come with error code 404

I've an issue while i'm trying to delete a driver from mySQL db.
Calling my function and passing mapped id (it's working):
<button id="deleteRent" onClick={DeleteVehicles.bind(vehicle.id)}>Delete</button>
Here is my react code:
const DeleteVehicles = (CarId) => {
Axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
.then((response) => {
if (response) {
console.log(response)
alert("Sikeres Törlés")
navigate("/admin");
}
else {
console.log("törlési hiba")
}
})
}
and here is my node express request:
app.delete('/vehicleDelete/:CarId'), async (req, res) => {
db.query("DELETE FROM products WHERE id = ?", req.params.CarId,
(err, result) => {
console.log(err)
console.log(result)
if (result) {
res.send(result);
}
})
}
any idea?
axios should be lowercased:
axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
Be careful with the closing parentheses on the express code:
app.delete('/vehicleDelete/:CarId', async (req, res) => {
db.query("DELETE FROM products WHERE id = ?", req.params.CarId, (err, result) => {
if (err) return res.status(500).send('Error')
res.status(200).send(result);
})
})
You should run this:
app.delete('/vehicleDelete/:CarId'), (req, res) => {
// make sure your are getting CarId that exists
// and then you delete it
db.query(`DELETE FROM products WHERE id = ${req.params.CarId}`,
(err, result) => {
console.log(err)
console.log(result)
if (result) {
res.send(result);
}
})
}
Also, you don't need to add async as your not using await for the query. The result gives you an object that might look like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
Now, when you say you receive the 404 status code, it means that you don't have the route on which the request is made. So, http://localhost:3001/vehicleDelete/${CarId} you need to register the route properly at the server.
You should add the catch blocks with Promises, it is recommended practice.
const DeleteVehicles = (CarId) => {
Axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
.then((response) => {
if (response) {
console.log(response)
alert("Sikeres Törlés")
navigate("/admin");
}
else {
console.log("törlési hiba")
}
}).catch(console.log);
}

Axios - How to fix - POST URL net::ERR_CONNECTION_RESET

How to fix this error message?
[xhr.js?b50d:178 POST http://localhost:3000/editor/add net::ERR_CONNECTION_RESET][1]
It works and append data, but I get this error message...
My API looks like this:
app.js
app.post('/editor/add', function (req, res) {
let articleData;
let textData;
let article = {
title: req.body.title,
content: req.body.content
}
fs.readFile(urlPath, 'utf8', (err, data) => {
if (err) {
console.log('readfile => ' + err);
} else {
articleData = JSON.parse(data);
articleData[article.title] = article.content;
textData = JSON.stringify(articleData, null, 2);
fs.writeFile(urlPath, textData, 'utf8', (err) => {
if (err) {
console.log('write file => ' + err);
} else {
console.log('Finished writing');
}
});
}
});
});
And my Axios POST method looks like this.
editor.vue
submitEditor: function() {
var self = this;
self.$axios({
headers: {
"Content-Type": "application/json"
},
method: "post",
url: "http://localhost:3000/editor/add",
data: {
title: "test5",
content: self.html
}
})
.then(res => {
console.log(res);
})
.catch(error => {
if (!error.response) {
// network error
this.errorStatus = "Error: Network Error";
} else {
this.errorStatus = error.response.data.message;
}
});
}
I use Vue/cli, I separate my client code and my server code. They are on a separate folder. I put Vue/cli in my client folder, and express.js in my server folder.
Thank you in advance!
Try sending a response from your route:
fs.writeFile(urlPath, textData, 'utf8', (err) => {
if (err) {
console.log('write file => ' + err);
} else {
console.log('Finished writing');
res.json({ msg: 'success' }); // send the client something
}
});

Nodejs Promise "res.end is not a function" error

I'm refactoring my code to remove a "callback hell" using Promises, but encountered an error that I cannot pass. My code receives list of IDs and processes them making few database calls, that is why I had this "callback hell".
Everything worked fine until Promises. The res is equal 0 when I had to respond back to the client.
function processVMDelete(returnedVMIDs){
return new Promise((resolve, reject) => {
var mariasqlClient = dbConnection();
mariasqlClient.query( sqlUpdateDELETE_STATE_ByVMID, [
'DELETE',
returnedVMIDs
], function(err, rows) {
if (err){
reject(err);
}
console.log('finish update');
// dont' need to return anything here
resolve(0);
});
mariasqlClient.end();
});
}
function getListExpVM(){
return new Promise((resolve, reject) => {
var vmList = [];
var mariasqlClient = dbConnection();
mariasqlClient.query( sqlSearch_ByUSERNAMEAndSTATE, [
requesterUsername,
'ACTIVE'
], function(err, rows) {
if (err){
reject(err);
}
vmList = filterExpiredVMs(rows);
var response = {
status : 200,
success : 'Successfull',
data : vmList,
requester: requesterUsername
};
resolve(response);
});
mariasqlClient.end();
});
}
router.post('/processVMs', function(req, res) {
var returnedVMIDs = JSON.parse(req.body.data);
processVMDelete(returnedVMIDs)
.then(res => {
console.log('done');
// check if there is more available for the user:
getListExpVM()
.then(response => {
console.log('sending back list of VMs');
//===>>> ERROR HERE: res.end is not a function
res.end(JSON.stringify(response));
})
.catch(err => {
console.log('error', err.message);
logger.error("Error getting expired VMs: " + err.message);
//===>>> ERROR HERE: res.send is not a function
res.status(500).send({error: err.message})
});
})
.catch(err => {
console.log('error', err.message);
logger.error("Error processing VMs: " + err.message);
//===>>> ERROR HERE: res.send is not a function
res.status(500).send({error: err.message})
});
});
You've redefined res with this:
processVMDelete(returnedVMIDs)
.then(res => {...})
This will hide the higher scoped res associated with the overall request (the one you need to use for res.end()). Change the name of this one to something else like result and then change the corresponding references that use this result.

AWS Lambda NodeJS, can't make external connection

So, I'm trying to do a basic thing: Connect to an external REST-API from my AWS Lambda script.
This API hosts a list of holidays.
But, whenever I try to execute the code it just times out (max lambda execution time reached).
So I created this wrapper function, that is capable of handling 4 different ways of doing GET requests, but all of them perform the same.
const request = require('request')
const https = require('https')
const axios = require('axios')
const superagent = require('superagent')
let test = (type = "") => {
return new Promise((resolve, reject) => {
debug("Fetching with: " + type)
const d = new Date()
if(type == "superagent"){
superagent.get('https://holidayapi.pl/v1/holidays?country=DK&year=' + d.getFullYear())
.query({ country: 'DK', year: '2019' })
.end((err, res) => {
if (err) {
console.log(err)
reject(err)
} else {
console.log(res)
resolve(res)
}
})
} else if(type == "axios"){
axios.get('https://holidayapi.pl/v1/holidays?country=DK&year=' + d.getFullYear())
.then(response => {
debug(response)
resolve(response)
})
.catch(error => {
console.log(error)
reject(error)
})
} else if(type == "https"){
const req = https.get("https://holidayapi.pl/v1/holidays?country=DK&year=" + d.getFullYear(), (resp) => {
let data = ''
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation)
resolve([])
})
})
.on('error', (e) => {
debug(e)
reject(e.message)
})
req.end()
} else if(type == "request"){
request('https://holidayapi.pl/v1/holidays?country=DK&year=' + d.getFullYear(), { json: true }, (err, res, body) => {
debug(err)
debug(res)
debug(body)
if (err) reject(err)
else resolve(body.holidays)
})
} else {
reject("Mangler type")
}
})
}
exports.connect_test = (event, context, callback) => {
test(event.pathParameters.type)
.then((rsp) => {
callback(null, JSON.stringify(rsp, null, 2))
})
.catch((err) => {
callback(null, JSON.stringify(err, null, 2))
})
}
The debug function is a map to console.log, that checks if the NODE_ENV is "dev".
I presume the default VPC has got internet connectivity, So if it's in the default it should just work (just increase the default timeout on the lambda to something reasonable).
If its inside a VPC then you need to have NAT Gateway/NAT instance configured for that VPC to have internet connection or pair with another VPC that has an internet access(Inside the VPC lambda need to have appropriate role and subnet).
This might help you aws docs

Mongoose remove and create in get route

I have a small issue with mongoose, what I am doing is getting data from online rss feeds, parsing it, and passing it to an array, from which I feed a mongoose model, and all this happens in the get route, what I want to accomplish is delete all the data first from the mongoose model and then populate it with the new data, but it always either deletes the data all together, since the parser iterates a few times, or it doesn't delete anything and the data just keeps adding to the model.
Here's my code
'use strict';
const Promise = require('bluebird');
const request = require('request');
const FeedParser = require('feedparser');
const express = require('express');
const router = express.Router();
const xray = require('x-ray')();
var Post = require('../models/post');
var dataArray = [];
router.get('/', function (req, res) {
const fetch = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error(`Bad URL (url: ${url}`));
}
const feedparser = new FeedParser();
const items = [];
feedparser.on('error', (e) => {
return reject(e);
}).on('readable', () => {
// This is where the action is!
var item;
console.time('loading')
while (item = feedparser.read()) {
items.push(item);
}
}).on('end', () => {
resolve({
meta: feedparser.meta,
records: items
});
});
request({
method: 'GET',
url: url
}, (e, res, body) => {
if (e) {
return reject(e);
} else if (res.statusCode != 200) {
return reject(new Error(`Bad status code (status: ${res.statusCode}, url: ${url})`));
}
feedparser.end(body);
feedparser.on('end', function () {
console.log('Done');
});
});
});
};
Promise.map([
'url',
'url',
'url',
'url'], (url) => fetch(url), { concurrency: 4 }) // note that concurrency limit
.then((feeds) => {
feeds.forEach(feed => {
feed.records.forEach(record => {
dataArray.push(record);
});
});
}).catch(function (error) {
console.log(error);
});
Post.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('collection removed');
}
});
dataArray.forEach(post => {
Post.create({
title: post.title,
content: post.description,
created: post.date,
image: post['rss:image']['#'],
link: post.link
}, function (err, newPost) {
console.log(newPost.title);
});
});
Post.find({}, function (err, posts) {
if (err) {
console.log(err);
} else {
res.render('index/home', {
posts: posts
});
}
});
});
module.exports = router;
None of this is going to run synchronously. You can do Something like this :
'use strict';
const Promise = require('bluebird');
const request = require('request');
const FeedParser = require('feedparser');
const express = require('express');
const router = express.Router();
const xray = require('x-ray')();
var Post = require('../models/post');
var dataArray = [];
const fetch;
router.get('/', function (req, res) {
Post.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('collection removed. Starting to fetch Posts from Service');
fetch = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error(`Bad URL (url: ${url}`));
}
const feedparser = new FeedParser();
const items = [];
feedparser.on('error', (e) => {
return reject(e);
}).on('readable', () => {
// This is where the action is!
var item;
console.time('loading')
while (item = feedparser.read()) {
items.push(item);
}
}).on('end', () => {
resolve({
meta: feedparser.meta,
records: items
});
});
request({
method: 'GET',
url: url
}, (e, res, body) => {
if (e) {
return reject(e);
} else if (res.statusCode != 200) {
return reject(new Error(`Bad status code (status: ${res.statusCode}, url: ${url})`));
}
feedparser.end(body);
feedparser.on('end', function () {
console.log('Done');
});
});
});
};
}
});
Promise.map([
'url',
'url',
'url',
'url'], (url) => fetch(url), { concurrency: 4 }) // note that concurrency limit
.then((feeds) => {
feeds.forEach(feed => {
dataArray = dataArray.concat(feed.records);
/*feed.records.forEach(record => {
dataArray.push(record);
});*/
});
console.log('inserting posts in the collection');
dataArray.forEach(post => {
Post.create({
title: post.title,
content: post.description,
created: post.date,
image: post['rss:image']['#'],
link: post.link
}, function (err, newPost) {
console.log(newPost.title);
});
});
console.log("Fetching posts from the collection");
Post.find({}, function (err, posts) {
if (err) {
console.log(err);
} else {
res.render('index/home', {
posts: posts
});
}
});
}).catch(function (error) {
console.log(error);
});
});
module.exports = router;
I haven't tested this. Please test it on your end. Let me know if there's an error or something.

Resources