http server-side node.js data - javascript

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.

Related

How to retrieve a response when the request is sent by ajax (XMLHtttpRequest)

/* the following **frontend** function is invoked to
send a new post (in json) to the node server */
addPost(postData) {
const xhr = new XMLHttpRequest();
xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(postData));
}
/* the following **server** code picks up the request
from the function above */
app.post('/posts', bodyParser.json(), (request, response) => {
new Promise(resolve => {
// code to add request.body to database will be here
resolve(request.body);
})
.then(data => response.send(data)); // *** How do I retrieve
} // *** this "data" in
); // *** my frontend code?
Hi all,
The top part of my code (frontend) is an ajax that sends a request in json format.
The bottom part of my code (node/express server) does the following:
1) receives the request
2) inserts "request.body" in a database
3) sends a response back to the frontend.
This response is a Promise containing the request.body. How do I retrieve this response in my frontend code? It seems that ajax helps me send requests, but doesn't do anything about retrieving the response that comes back.
Thanks!
P.S. Since this data was originally sent from the frontend, one might say the frontend already has this data. However, I just want to know, in general, how to retrieve a response when the request is sent by ajax.
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
}
xhr has an event handler onreadystatechange ,
you can say that the request has been successful when xhr.readyState == XMLHttpRequest.DONE.
more detailed doc on this can be availed # https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
you can also get the status code of the http request from xhr.status
XMLHttpRequest is pretty Useful API, but it is too low level, it is now being superseded by FETCH API, which is awesome, it also supports promise interface, that means you can use .then and .catch , or the newer async/await.
you can read it up here # https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
and an example # https://googlechrome.github.io/samples/fetch-api/fetch-post.html

sending hexadecimal file data using post to different domain

Is it possible to send this form of the request using multipart form data, by manually constructing the headers. Also for this file what will be the content/mime type. When I created this form of the request the request reached the server, but the data received there is null. Also I get an error message for cross domain request as it's not a jsonp. Is there a way to accomplish this as its a post request. Java is used as server-side.
For your Cross-Domain request, you will need to add the Cross-Origin Resource Sharing (CORS) headers to the server: something like Access-Control-Allow-Origin: *. Not entirely sure where this would go in Java servers, but if you have previously set headers before for the server, the CORS header would go along with that. I'm not entirely sure about sending raw binary via JavaScript. Perhaps someone else knows better.
Basically, you just perform xhr POST/PUT request. But first get the file into an input.
Here is a put example I found in one my old project:
const fileInput = document.getElementById('file-input')
const file = fileInput.files[0]
const xhr = new XMLHttpRequest()
xhr.onerror = (e) => {
console.log(e)
}
xhr.upload.addEventListener('progress', (e) => {
// handle notifications about upload progress: e.loaded / e.total
const { loaded, total } = e
console.log(`${loaded} / ${total}`)
}, false)
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status >= 200 && xhr.status <= 299) {
// upload completed
}
}
}
xhr.open('PUT', 'linktoupload', true)
xhr.setRequestHeader('Content-Type', 'application/octet-stream')
xhr.send(file)

Why does this email sending function not work?

Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.

How to use my local API in a javascript file?

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();

How to get only response headers from XMLHttpRequest

Is it possible to get only response headers from XMLHttpRequest without downloading file data?
If the server you are making the request to supports the method, it sounds like what you want is to make an HTTP HEAD request. See the HTTP spec.
For example compare the output from curl -v -X GET https://github.com and curl -v -X HEAD https://github.com.
Also see HTTP HEAD Request in Javascript/Ajax?
Using JavaScript (as specified in the question) simply use a head request via AJAX:
var xhr = new XMLHttpRequest();
var method = 'head';
var url = 'https://www.example.com/';
xhr.open(method,url,true);
xhr.send(null);
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4)
{
console.log(xhr.getAllResponseHeaders())
}
}
Firstly, the answer from John fixes this issue but it got downvoted because it didn't have enough of an explanation.
So here is the fix with an explanation as well as an extra bit that you can add as well.
Client side solution is as follows (I am using the status code as the example):
function checkStatus(url) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('HEAD', url, true)
request.onreadystatechange = () => {
if (request.readyState >= 2) {
resolve(request.status)
request.abort()
}
}
request.onerror = (e) => {
reject(e)
}
request.send()
})
}
The reason why this works is for two reasons.
Firstly we are passing HEAD in as the method instead of GET this should be enough on its own, but if you want to do more, you can move onto the second reason.
The second reason this works is because of the readyState states.
0 = UNSENT
1 = OPENED
2 = HEADERS_RECEIVED
3 = LOADING
4 = DONE
At state 2 the headers are ready to be viewed. This means you can then return whatever you need and/or abort the rest of the request preventing any further data being downloaded.
Worth noting you can also do this with request.onprogress at stage 3.
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState and https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods for more details.

Categories

Resources