Server is restarted after an axios request with express - javascript

My problem is, My project's server is restarted After an axios request with express.
I can see http://localhost:3000/__webpack_hmr 200 OK in console of chrome.
when I add vocabulary to data or remove that, server is restarted.
This is the vue client code. (github link to file)
methods: {
addVocabulary () {
var vm = this
this.$validator.validateAll().then((result) => {
if (result) {
axios.post('/api/vc/add', {
vocabulary: this.vocabulary
}).then(function (response) {
vm.vocabularies = response.data
}).catch(function (error) {
console.log(error)
})
this.vocabulary = ''
} else {
console.log('Not valid')
}
})
},
remove (id) {
var vm = this
axios({
method: 'delete',
url: '/api/vc/remove',
data: {id: id},
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
vm.vocabularies = response.data
}).catch(function (error) {
console.log(error)
})
}
}
And this is the server side code.link to file
router.post('/vc/add', function (req, res, next) {
if (!req.body) return res.sendStatus(400)
let vocabulary = req.body.vocabulary
let objVocabulary = {}
objVocabulary.id = 10
objVocabulary.content = vocabulary
vocabularies.push(objVocabulary)
fse.outputJson(file, vocabularies, err=>{
console.log(err);
fse.readJson(file, (err, data) =>{
res.json(data);
})
})
})
/* DELETE remove voca */
router.delete('/vc/remove', (req, res, next) =>{
if (!req.body) return res.sendStatus(400)
let id = req.body.id
var index = vocabularies.findIndex(voca => voca.id === id);
vocabularies.splice(index,1);
fse.outputJson(file, vocabularies, err=>{
console.log(err);
fse.readJson(file, (err, data) =>{
res.json(data);
})
})
})
Here's my project link to github,
I don't know why..

I see that you are using backpack.
Their documentation quotes: Live reload (on saves, add/delete file, etc.)
So, if you the JSON file you are manipulating in your server code is in a folder watched by backpack, hot module reload will kick in and restart the server.
Solution: Move the json to some other directory --> your database shouldn't be part of your source code anyways.

Related

Unable to fetch data from MySQL database with Fetch API

I'm able to post successfully to MySQL database with Fetch API. The problem I'm having is trying to retrieve data from my database.
client.js:
const output = document.getElementById('output');
const username = document.querySelector('#username');
const date = document.querySelector('#date');
const submitbtn = document.querySelector('#submitbtn');
const commentOutput = document.querySelector('#message');
const form = document.querySelector('#form');
const comments = document.getElementById('message')
form.addEventListener('submit', function(e) {
e.preventDefault(e);
sendMessage();
let formMessage = new FormData(form);
formMessage.append('api-key', 'myApiKey');
fetch('http://localhost:5502/superhero', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({ comments: comments.value })
}).then(function(response) {
console.log(response)
console.log(JSON.stringify({ comments: comments.value }))
return response.json()
}).then(function(data) {
console.log(data);
}).catch(function(error) {
console.log(error);
});
})
submitbtn.addEventListener('click', function() {
fetch('http://localhost:5502')
.then(response => {
if (response.ok) {
console.log('success')
} else {
console.log('failure')
}
return response.json();
})
.then(data =>
console.log(data))
.catch(error => console.log('Error'))
var newUser = document.createElement("div");
var newName = document.createElement("h5");
var newDate = document.createElement("h5");
var newMessage = document.createElement("h6");
newName.textContent = comments.value;
newDate.textContent = message.value;
newMessage.textContent = message.value;
output.appendChild(newName);
output.appendChild(newDate);
output.appendChild(newMessage);
output.appendChild(newUser);
})
The problem here is the fetch method under the submitbtn:
Output:
index.js:
router.post("/superhero", function(req, res) {
const user = req.user;
const comments = req.body.comments;
sqlDatabase.query("INSERT INTO comments (user_id, comments) VALUES (?, ?)", [user, comments],
function(error, results, fields) {
console.log(results);
console.log(comments);
console.log('This is: ', comments)
console.log(error)
if (error) throw error;
});
})
router.get("/superhero", authenticationMiddleware(), function(req, res, err) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results, fields) {
if (error) throw error;
console.log(results);
console.log(error);
res.render('superhero');
})
})
I want to retrieve that data under router.get
Hope this is enough details. Thanks in advance. Noob by the way.
The res.send actually send back the JSON response
router.get("/superhero", authenticationMiddleware(), function(req, res, err) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results, fields) {
if (error) throw error;
console.log(results);
console.log(error);
res.send({heros: results}); //<-- send back the JSON response
})
})
Also, you can add condition if you're rendering on the server side as well
if (req.accepts('json')) {
res.send({hero: 'superhero'}); // <-- try sending back JSON object but rather a string
// OR
res.send({heros: results});
else {
res.render('superhero');
}
If you're using Express then you can use response.json method as well.
Finally got the results I wanted. I just created another api for retrieving data from my server file and changed
this:
fetch('http://localhost:5502/superhero')
to:
fetch('http://localhost:5502' + '/get_messages')
app.get("/get_messages", function(request, result) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results) {
result.end(JSON.stringify(results));
console.log(results);
});
});
So I have a route for rendering a view, and one for retrieving the data

I can't insert data to my database (mysql)

I'm learning now MySQL and I have a some problem. I tried to make a post request to my db::
My code from client side:
async function sendValues() {
const settings = {
method: 'post',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(product)
}
try {
const fetchResponse = await fetch('http://localhost:9001/products', settings);
const data = await fetchResponse.json();
console.log(data) // what the user send
} catch (err) {
return err
}
}
My code from server side:
router.post('/', (req, res) => {
const { c_id, p_name, p_price } = req.body
const q =
`
INSERT INTO products (c_id,p_name,p_price)
VALUES("${c_id}", "${p_name}" , "${p_price}")
`;
con.query(q, (err, result, fields) => {
if (err) throw err;
res.json(result)
});
});
There are two possible mistakes:
1.check the connection between client and server. as mentioned above.
2.check the table name, data type of attributes, name of attributes you are providing.
The rest endpoint is / and you are calling products change your backend code as below.
router.post('/products', (req, res) => {
const { c_id, p_name, p_price } = req.body
const q =
`
INSERT INTO products (c_id,p_name,p_price)
VALUES("${c_id}", "${p_name}" , "${p_price}")
`;
con.query(q, (err, result, fields) => {
if (err) throw err;
res.json(result)
});
});

Send back data from node.js to client side javascript

what I´m trying to do is the following I already set a fetch connection from client side JS to the server Node.JS when a person click on a button in HTML which triggers that in the server side looks for an element in the MongoDB database in it find´s it, but my question is how do I send that found element back to the client side JS.
Javascript Code:
var button = document.getElementById("1");
button.addEventListener("click", idss);
function idss() {
var id = this.id;
var data = {
name : id
}
fetch("/clicked", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(function(response) {
if(response.ok) {
console.log('awesome');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
NODE JS:
app.post("/clicked", (req, res) => {
var pro = (req.body.name);
Number(pro);
Product.findOne({"id": pro}, function(err, foundLList) {
if(err) {
console.log(err);
} else {
console.log(foundLList); //THE ELEMENT IS FOUND
}
}
);
});
What I´m trying to do is to send the found element to Javascript so I can added to another variable.
You have to use res object to send data back to client. Your node code will be:
app.post("/clicked", (req, res) => {
var pro = (req.body.name);
Number(pro);
Product.findOne({
"id": pro
}, function(err, foundLList) {
if (err) {
console.log(err);
return res.status(500).json({
ok: false,
error: err
});
} else {
console.log(foundLList); //THE ELEMENT IS FOUND
return res.status(200).json({
ok: true,
data: foundLList
});
}
});
});
and on client side, you can read the data like this:
fetch("/clicked", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(function(response) {
if (response.ok) {
console.log('got data: ', response.data);
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}

error in getting the response, if nodejs server send response after some delay

I am trying to upload the image, and then nodeJS server send the path of that image folder back as a response.
But When I sending the response after performing some task, nothing happening on angular-side.
this is my component.ts file.
uploadImage() {
const formData = new FormData();
formData.append('photo', this.image);
const obj$ = this.userService.uploadData(formData);
obj$.subscribe(data => {
console.log(data); //// nothing happening.
if (data.success) {
this.uploadForm.patchValue({
document: data.url
});
}
});
}
and my service.ts
uploadData (uploadImage) {
return this.http.post<UploadPhoto>('/user/upload', uploadImage);
}
and my app.js
router.post('/upload' ,upload.single('photo'), (req,res) => {
console.log(req.file);
const body = req.file;
cloudinary.uploader.upload(body.path, (err, result) => {
if (err) {
console.log(err);
return;
}
console.log(result);
res.status(200).json({
url: result.url,
success: true
});
});
});
But when I am sending response without performing any task, it works fine like
router.post('/upload' ,upload.single('photo'), (req,res) => {
console.log(req.file);
const body = req.file;
res.status(200).json({
url: 'hello',
success: true
})
});
I don't know why is this happening.
Please someone help me.
When an error occurs in your uploader you're returning the error to the console and then ending execution. If there is an error in the asynchronous method you must pass it to the next() function so that express can handle it.
router.post('/upload' ,upload.single('photo'), (req,res, next) => {
console.log(req.file);
const body = req.file;
cloudinary.uploader.upload(body.path, (err, result) => {
if (err) {
console.log(err);
next(err);
}
else {
console.log(result);
res.status(200).json({ url: result.url, success: true });
}
});
});

Asynchronous Javascript Request Issue (Node, request-promise module)

I am building an application and having an issue with making a request from the client, sending it to my server, having the server make the API call and then send the result back to the client. I am using Node and the Request-Promise module.
Here is the client side code:
$(document).ready(function() {
var artistSearch = () => {
const q = $('.artistName').val();
$.ajax({
type: "POST",
url: "http://localhost:3000/request",
data: {artist: q},
})
.done(function(data) {
console.log('data: ', data)
})
};
$(".artistSearch").submit( () => {
artistSearch();
});
});
This successfully makes a request to the server:
app.post('/request', (req, res) => {
const artist = req.body.artist;
const searchURL = "https://api.spotify.com/v1/search? q="+artist+"&type=artist";
var targetObj;
var options = {
uri: searchURL
};
rp(options)
.then(function (data) {
console.log(data);
res.send(data);
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
});
Which ultimately successfully grabs the data from the API call, but never sends it back to the client! If I do res.send() outside of my .then promise, I can receive data on the client end.
Is there something I am missing? Thanks in advance!
Try this
var options = {
uri: searchURL,
simple: false,
};
rp(options)
.then(function (data) {
console.log(data);
res.status(200).send(data).end();
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
I think the client did receive data, but the connection didn't terminate correctly as it thinks there are more data. This is because you didn't specify the header and the module http couldn't figure out the content-length.
rp(options)
.then(function (data) {
console.log(data);
// res.send(data);
// assume data is JSON.
res.setHeader (200, {'Content-Type': 'application/json',
'Content-Length':data.byteLength});
res.end(data); //Send data immediately.
})
...
If data is a string, you will need to use data.length instead. In fact, if data is a string, then by default the header is {'Content-Type': 'application/json', 'Content-Length':data.length}

Categories

Resources