How to use my local API in a javascript file? - javascript

I have a file api.js which contains something along the lines of this:
exports.showAll = function(req, res) {
Obj.find(function(err, Objs) {
res.send(Objs);
});
}
My server has the line:
app.get('/all', api.showAll);
When I load /all in the browser, I get the JSON, but I want to get this JSON into a client-side JS file, so I can display the JSON data beautifully on a webpage.
How do I use my server-side API in a client-side JS file?

To make a call to a server and work with the result, you need to use AJAX. AJAX stands for Asynchronous JavaScript and XML but the reality is that you can make these kinds of call through other languages and without retrieving XML. Here's a simple example of how to make a request to your server:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
// Verify that the request is done and completed successfully
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var json = xhr.responseText;
var data = JSON.parse(json); // Parse the JSON into an actual object/array
console.log(data);
} else {
console.log('Something went wrong');
}
}
};
xhr.open('GET', '/all');
xhr.send();

Related

How to everytime reload web, and get the newest data from back-end

What my purpose is below
Visting a web and the js.file in this web will load php file, and it will return data to html.
It's meaning every time when I reload web, I will get newest data.
I have try this in js.file
let XML = new XMLHttpRequest();
XML.open('post', url, true);
XML.send('mydata');
then use responseText to get data I want
Indeed, I don't need send any data.
I can do what I want to do, but I am not sure this way is right or not.
Because I think ajax should not use in this case, it must be send something and return something.
What you are saying is you only want to get data without sending anything which is called a http get request, you can do that as below.
function get(url)
{
var xm = new XMLHttpRequest();
// false for synchronous
xm.open("GET",url,false);
xm.send(null);
return xm.responseText;
}
console.log(get('your Url'));
You need to specify the url of your Http Endpoint ( Back-End ).
If your are making a asynchronous request then below code works,,
function get(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
// true for asynchronous
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
get('your url',(responseText)=>{
console.log(responsetext);
});

Receive Single Data from xml

I have brought some data from the server using ajax.
Now I want to, not bring all the data, only the name is inter.
How can I do this?
that my code
const url = 'https://jsonplaceholder.typicode.com/users'
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
console.log(xhr.response);
}
xhr.open('GET', url)
xhr.send()
You could loop through the xhr response and get the name of the users.
xhr.onreadystatechange = () => {
if(xhr.response) {
let userResponse = JSON.parse(xhr.response);
for (index in userResponse) {
console.log(userResponse[index].name);
}
}
}
You can even save it in a temporary variable and make further manipulations.
But if you meant bringing just the name from the server, it is not possible unless the server exposes an API to do so.
If you have access to the server you could create an API to do this. But, if your server had used graphQL, it is possible to make queries while making API requests like you asked for.

http server-side node.js data

I have html page using jQuery.
I want to send requests to node server but I don't know how to response to different requests, in other words how to distinguish between get\post request and how read the request body (undreastend what the user wanted) and response according to it.
var http = require("http");
function serve(request, response)
{
response.writeHead(200, {"Content-Type": "text/plain"});
}
http.createServer(serve).listen(3001);
and in the client side, same question - how to send data?
Window.onload = function () {
Document.getElementById('GoButton').click = function() {
var xhr = new XHRObject();
xhr.open("get","http://127.0.0.1:1337",true);
xhr.onreadystatechange= function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
request.send(null);
};
};
and last thing : all this request&response should use json .
To decide what you need to put in your response message, you need to check your request property. Taking a quick look at the api documentation, you can see that request is an instance of IncomingMessage, and that it has a property called method.
If you want to reply something specific for all POST requests, you should check if request.method === 'POST'.
Either way, you're apparantly completely new to node, in which case you should probably read up a bit more. http://nodebeginner.org is a good resource to start with.

Using javascript to submit a post request to a server

I am working on a web crawler that can integrate with our partner portals and submit post requests to make bid changes.
The trouble is that the crawler runs in an environment which cannot execute jQuery, only native Javascript.
I have determined that the following AJAX code successfully sends the post request:
$.ajax({
type: "POST",
url: "http://acp.example.com/campaigns/122828",
data: "data-string"
});
Is there a way to translate the above statement into native javascript so that the crawler can execute it?
UPDATE
When executing hex494D49's native Javascript below, I am receiving a "NetworkError: 404 Not Found - http://acp.fyber.com/campaigns/122828" message.
However, when I execute the original AJAX code in firebug, it successfully sends the POST request.
Any idea why the same url would return a 404 error using native Javascript as opposed to AJAX?
Thanks
Sending AJAX request using POST method
var xhr = new XMLHttpRequest();
var url = "url";
var data = "email=hey#mail.com&password=101010";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(data);
Sending AJAX request using GET method
xhr = new XMLHttpRequest();
var url = "url?email=hey#mail.com&password=101010";
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
}
xhr.send();
To avoid unexpected requests to the server, it's a good practice to use encodeURIComponent() method on any user-entered parameters that will be passed as part of a URI.

What should a proper GET request and response look like in Node.js

I am working on a small project using Node.js.
The objective is to send an HTTP Request to an array of websites and display what they return to me.
First someone helped me to figure out that I needed a specific Node.js module (XMLHttpRequest). So I "required" it after installing it with NPM. Then I instantiate it.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
//I don't think I need this
xmlHttp.send(null);
//Log some stuff to the console, namely the "response"
console.log(xmlHttp.responseText);
console.log(xmlHttp.statusText);
console.log("Finished!");
Now I believe what this will do is send a GET message to "theUrl", and then save the response in the xmlHttp Object's responseText member.
So now I should have a response. I should be able to print that as text (console.log(xmlHttp.responseText);). What should be in this response?
I expect to get something like "200 OK" but that is nowhere in the response I get. Am I going about this in the right way?
I plan on using the Async Node.js module to send a request like this to an array of URLs, trim up their response (name of the website name, the response status code, and each of the response headers).
You can use below;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
// responseText => response body as string
// status => 200 is OK, 404 page not found
}
};
xhr.open("GET", "yor_url");
xhr.send();
responseText: response body as string
status: 200 is OK, 404 page not found

Categories

Resources