Send back data from node.js to client side javascript - 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);
});
}

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

Getting a json from an api with fetch js

I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:
function get(){
fetch('http://localhost:8082/marca/listar', {
method: 'GET',
headers: {},
mode: 'no-cors', // <---
cache: 'default'
})
.then(Response => { return Response.json() })
.then(data => {
console.log(data.nombre)
});
}
This is the url of the api
And I get the following error:
console message image
Per https://developer.mozilla.org/en-US/docs/Web/API/Body/json have you tried:
response.json().then(data => {
// do something with your data
});
it is because the response you get from the server is an array not JSON object
so treat it as such
fetch('http://localhost:8082/marca/listar',
{ cache: 'default' })
.then(function (response) {
if (response.status !== 200) {
return;
}
response.json().then(function (data) {
data.forEach((element) => {
element.whatYouWant; /* Change (whatYouWant) to your desired output */
})
})
})
.catch(function (err) {
console.log('Fetch Error :-S', err);
});

SyntaxError: Unexpected end of input in fetch API

I face a new problem that has been asked before in this link. But It is not relevant to my problem.
What I have implemented is a very simple API using nodejs, express-framework and mongoose.
The problem is with fetch API. I want to submit some ID and post it to the server. In the server side I redirect it to the proper URL base on the ID that user entered. Whenever I test this part, this error is being raised in front-end side and points to return response.json() line.
SyntaxError: Unexpected end of input
Here is my code:
Front-End:
function submitCode(){
var nationalCode = document.getElementById('nationalCode').value
var data = {
nationalCode: nationalCode,
creationDate: new Date().toLocaleDateString()
}
fetch('/submit', {
method: 'POST',
redirect:'manual',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
},
).then(response => {
return response.json()
}).then(jsonData => {
console.log('success:', jsonData)
history.pushState(null, null, "/lashkhor")
}).catch(e => {
console.log('error:', e)
return e
})
}
Back-End:
app.post('/submit', (req, res) => {
var nationalCode = req.body.nationalCode
var creationDate = req.body.creationDate
query = {'nationalCode': nationalCode}
nationalCodeModel.find(query, (err, success) => {
if (err) {
console.log('error:', err)
}
else if (success.length == 0){
nationalCodeModel.create({
nationalCode: nationalCode,
creationDate: creationDate
})
console.log('salam khoshgele daei!')
res.redirect('/khoshgeledaei')
}
else if (success.length > 0) {
console.log('lashkhor detected')
res.redirect('/lashkhor')
}
})
})
app.get('/lashkhor', (req, res) => {
console.log('here')
res.send('salam')
})
I can't find any hint to solve it. I would be thankful if anyone could help me.
PS: Whole code is available in this repository
Thanks!
You are trying to parse text into json.
You can use res.json() instead of res.send() from your backend.

Server is restarted after an axios request with express

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.

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