How to send Object by Post request using native Ajax on NodeJS - node.js

I am trying to POST the input filed value as an object to the NodeJs controller. Here i am using native ajax POST method. And body-parser package on nodejs to access the POST request. But when i log the res.body i see its empty. I am new in Ajax and NodeJs. Sorry if i am making any obvious mistakes...
window.addEventListener("load" , () => {
let formSubmit = document.querySelector("#formSubmit");
formSubmit.addEventListener("submit", (e) => {
e.preventDefault();
let inputTodo = document.querySelector("#inputTodo").value;
let todo = {item : inputTodo};
let xhr = new XMLHttpRequest();
xhr.open("POST" , "/todo" , true);
xhr.setRequestHeader("Content-type", "application/json");
let data = todo;
console.log(data)
xhr.send(data);
location.reload();
})
});
app.post("/todo" ,urlencodedParser, (req, res) => {
console.log(req.body)
data.push(req.body);
res.json(data);
})

Looks like you are sending and undefined data object, for what i see in your code you never assign any value to the data variable before call the .send(data) method. So try with this and should work
xhr.send({id: 'example_id'});

Defining the method in template engine form as POST solved the problem for me. It's a GET method by default but somehow when we are using the jQuery Ajax we don't need to change the method. And it works fine. But if we want to use Native Ajax we must set the POST method in the form even when we are defining the type as POST.
form(
method="POST"
action="/Contact"
)

Related

How to Retrieve Data from Out of Axios Function to Add to Array (NEWBIE QUESTION)

I am working on building a blog API for a practice project, but am using the data from an external API. (There is no authorization required, I am using the JSON data at permission of the developer)
The idea is that the user can enter multiple topic parameters into my API. Then, I make individual requests to the external API for the requested info.
For each topic query, I would like to:
Get the appropriate data from the external API based on the params entered (using a GET request to the URL)
Add the response data to my own array that will be displayed at the end.
Check if each object already exists in the array (to avoid duplicates).
res.send the array.
My main problem I think has to do with understanding the scope and also promises in Axios. I have tried to read up on the concept of promise based requests but I can't seem to understand how to apply this to my code.
I know my code is an overall mess, but if anybody could explain how I can extract the data from the Axios function, I think it could help me get the ball rolling again.
Sorry if this is a super low-level or obvious question - I am self-taught and am still very much a newbie!~ (my code is a pretty big mess right now haha)
Here is a screenshot of the bit of code I need to fix:
router.get('/:tagQuery', function(req, res){
const tagString = req.params.tagQuery;
const tagArray = tagString.split(',');
router.get('/:tag', function(req, res){
const tagString = req.params.tag;
const tagArray = queryString.split(',');
const displayPosts = tagArray.map(function(topic){
const baseUrl = "https://info.io/api/blog/posts";
return axios
.get(baseUrl, {
params: {
tag: tag
}
})
.then(function(response) {
const responseData = response.data.posts;
if (tag === (tagArray[0])){
const responseData = response.data.posts;
displayPosts.push(responseData);
} else {
responseData.forEach(function(post){
// I will write function to check if post already exists in responseData array. Else, add to array
}); // End if/then
})
.catch(function(err) {
console.log(err.message);
}); // End Axios
}); // End Map Function
res.send(displayPosts);
});
Node.js is a single thread non-blocking, and according to your code you will respond with the result before you fetching the data.
you are using .map which will fetch n queries.
use Promise.all to fetch all the requests || Promise.allsettled.
after that inside the .then of Promise.all || promise.allsettled, map your result.
after that respond with the mapped data to the user
router.get('/:tag', function (req, res) {
const tagString = req.params.tag;
const tagArray = queryString.split(',');
const baseUrl = "https://info.io/api/blog/posts";
const topicsPromises=tagArray.map((tobic)=>{
return axios
.get(baseUrl, {
params: {
tag: tag
}
})
});
Promise.all(topicsPromises).then(topicsArr=>{
//all the data have been fetched successfully
// loop through the array and handle your business logic for each topic
//send the required data to the user using res.send()
}).catch(err=>{
// error while fetching the data
});
});
your code will be something like this.
note: read first in promise.all and how it is working.

Send variable from mongoose query to page without reload on click

I have a link on my site. When clicked it'll call a function that does a mongoose query.
I'd like the results of that query to be sent to the same page in a variable without reloading the page. How do I do that? Right now it is just rendering the page again with new query result data.
// List comments for specified chapter id.
commentController.list = function (req, res) {
var chapterId = req.params.chapterId;
var query = { chapterId: chapterId };
Chapter.find({ _id: chapterId }).then(function (chapter) {
var chapter = chapter;
Comment.find(query).then(function (data) {
console.log(chapter);
Chapter.find().then(function(chapters){
return res.render({'chapterlinks', commentList: data, user: req.user, chapterq: chapter, chapters:chapters });
})
});
})
};
You just need to make that request from your browser via AJAX:
https://www.w3schools.com/xml/ajax_intro.asp
This would be in the code for your client (browser), not the code for your server (nodejs).
UPDATE:
Here's a simple example, which uses jQuery to make things easier:
(1) create a function that performs and handles the ajax request
function getChapterLinks(chapterId) {
$.ajax({
url: "/chapterLinks/"+chapterId,
}).done(function(data) {
//here you should do something with data
console.log(data);
});
}
(2) bind that function to a DOM element's click event
$( "a#chapterLinks1" ).click(function() {
getChapterLinks(1);
});
(3) make sure that DOM element is somewhere in you html
<a id="chapterLinks1">Get ChapterLinks 1</a>
Now when this a#chapterLinks1 element is clicked, it will use AJAX to fetch the response of /chaptersLink/1 from your server without reloading the page.
references:
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.click/

How to call third party API inside a controller function in Node/Express?

Just playing around with my first Node/Express App.
What I am trying to do:
On submitting a form to /wordsearch (POST) the Wikipedia API should be called with the submitted keyword. After getting back the response from Wikipedia, I want to present it back to the user in a view. Basic stuff.
But I am missing some basic understanding of how to arrange that in NODE/JS. I read about callbacks and promises lately and understand the concepts theoretically, but seem to mix things up when trying to put it into code. If someone could shed light on where I am wrong, that would be highly appreciated.
Approach 1:
This is the controller function that is hit on submitting the form:
exports.searchSources = (req, res) => {
const term = req.body.searchTerm
const url = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${term}&limit=10&namespace=0&format=json`
const client = new Client()
client.get(url, function (data, response) {
//this causes the error
res.json(data)
})
}
=> Error: Can't set headers after they are sent.
I know, that the error stems from trying to set response headers twice or when the response is already in a certain state, but I don't see where that happens here. How can I wait for the result of the Wiki request and have it available in the controller function so that I can render it?
Approach 2:
Again, the controller function:
exports.searchSources = (req, res) => {
const term = req.body.searchTerm
const url = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${term}&limit=10&namespace=0&format=json`
const client = new Client()
const data = client.get(url, function (data, response) {
return data
})
res.json(data)
}
=> TypeError: Converting circular structure to JSON at JSON.stringify ()
This was just a try to make the response from Wiki available in the controller function.

angular2-rc1 http.post not working correctly

I am creating one angular2 app in which I am using http in my service to make POST call to mongoDB.
When I am making a POST call for the first time it is working fine i.e. entry is inserted into database correctly but when I am sending the data for second time it is not getting inserted.
If I am reloading the page after first insertion then its working fine.
I did some debugging and found that during second request my req.body is blank.
Here is my code:
page.service.ts
savePage(page: Object) {
this.headers.append('Content-Type', 'application/json');
let url = this.baseUrl+'/pm/pages/';
let data={};
data["data"]=page;
console.log(data); //this is printing both times correctly
//on second request data is blank where as it works correctly for first time
return this.http.post(url, JSON.stringify(data),{headers: this.headers})
.map((res: Response) => res.json()).catch(this.handleError);
}
Here is my data in req.body shown in node services.
First Request:
body:{
data:{
name: 'wtwetwet',
desc: 'wetwetwetetwte',
isPublic: true,
createdBy: 'Bhushan'
}
}
Second Request
body: {}
any inputs?
It looks more like a backend thing. You should however include the code that subscribes on this http call.
By the way, why are you using RC1? Angular 2 is now on RC5.
I finally realised that my method used to set content-type each time it was getting called.
Thus changing code from :
savePage(page: Object) {
this.headers.append('Content-Type', 'application/json');
let url = this.baseUrl+'/pm/pages/';
let data={};
data["data"]=page;
return this.http.post(url, JSON.stringify(data),{headers: this.headers})
.map((res: Response) => res.json()).catch(this.handleError);
}
to:
savePage(page: Object) {
this.headers=new Headers();
this.headers.append('Content-Type', 'application/json');
let url = this.baseUrl+'/pm/pages/';
let data={};
data["data"]=page;
return this.http.post(url, JSON.stringify(data),{headers: this.headers})
.map((res: Response) => res.json()).catch(this.handleError);
}
did the trick for me.
Actually we need to set headers only once while making a rest call,but in my code it was already set thus creating new Headers Object helped me clearing any previously set configurations.
Thanks for the help guys.

Sending additional data with programatically created Dropzone using the sending event

I have the following (simplified for example) angular directive which creates a dropzone
directives.directive('dropzone', ['dropZoneFactory', function(dropZoneFactory){
'use strict';
return {
restrict: 'C',
link : function(scope, element, attrs){
new Dropzone('#'+attrs.id, {url: attrs.url});
var myDropZone = Dropzone.forElement('#'+attrs.id);
myDropZone.on('sending', function(file, xhr, formData){
//this gets triggered
console.log('sending');
formData.userName='bob';
});
}
}
}]);
As you can see the the sending event handler I'm trying to send the username ("bob") along with the uploaded file. However, I can't seem to retrieve it in my route middleware as req.params comes back as an empty array (I've also tried req.body).
My node route
{
path: '/uploads',
httpMethod: 'POST',
middleware: [express.bodyParser({ keepExtensions: true, uploadDir: 'uploads'}),function(request,response){
// comes back as []
console.log(request.params);
//this sees the files fine
console.log(request.files);
response.end("upload complete");
}]
}
Here is what the docs say on the sending event
Called just before each file is sent. Gets the xhr object and the formData objects as second and third parameters, so you can modify them (for example to add a CSRF token) or add additional data.
EDIT
I dropped the programmatic approach for now. I have two forms submitting to the same endpoint, a regular one with just post and a dropzone one. Both work, so I don't think it's an issue with the endpoint rather with how I handle the 'sending' event.
//Receives the POST var just fine
form(action="http://127.0.0.1:3000/uploads", method="post", id="mydz")
input(type="hidden", name="additionaldata", value="1")
input(type="submit")
//With this one I can get the POST var
form(action="http://127.0.0.1:3000/uploads", method="post", id="mydz2", class="dropzone")
input(type="hidden", name="additionaldata", value="1")
OK, I've actually figured it out, thanks to Using Dropzone.js to upload after new user creation, send headers
The sending event:
myDropZone.on('sending', function(file, xhr, formData){
formData.append('userName', 'bob');
});
As opposed to formData.userName = 'bob' which doesn't work for some reason.
I would like to add to NicolasMoise's answer.
As a beginner in webdev I got stuck on how to obtain an instance of Dropzone. I wanted to retrieve an instance of Dropzone that had been generated by the autodiscovery feature. But it turns out that the easiest way to do this is to manually add a Dropzone instance after first telling Dropzone not to auto-discover.
<input id="pathInput"/>
<div id="uploadForm" class="dropzone"/>
<script>
$(document).ready(function(){
Dropzone.autoDiscover = false;
var dZone = new Dropzone("div#uploadForm", {url: "/api/uploads"});
dZone.on("sending", function(file, xhr, data){
data.append("uploadFolder", $("#pathInput")[0].value);
});
});
</script>
Serverside the data will be in request.body.uploadFolder
Nicolas answer is one possible solution to the problem. It is especially useful if you need to alter the file object prior to sending.
An alternative is to use the params option:
var myDropzone = new Dropzone("div#myId",
{ url: "/file/post", params: { 'param_1': 1 }});
cf. the documention
For those that are using thatisuday/ng-dropzone the callback methods are done as such:
<ng-dropzone class="dropzone" options="dzOptions" callbacks="dzCallbacks" methods="dzMethods"></ng-dropzone>
In a controller:
$scope.dzCallbacks = {
sending: function(file, xhr, form) {
console.log('custom sending', arguments);
form.append('a', 'b');
}
};

Resources