sending hexadecimal file data using post to different domain - javascript

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)

Related

XMLHttpRequest post files fails if the server doesn't read content but instead sends a response (even with code 200)

I'm using the following code to send files from a form to the server:
const request = new XMLHttpRequest();
const formElement = document.getElementById('form');
request.upload.addEventListener("progress", (e) => {
console.log("progress: " + e.loaded + "/" + e.total);
});
// request load handler (transfer complete)
request.addEventListener("load", function (e) {
console.log(e);
});
request.addEventListener("readystatechange", function (e) {
console.log(e);
});
// request error handler
request.addEventListener("error", function (e) {
console.log(e, request)
});
request.open("post", formElement.action);
request.responseType = "json";
request.send(new FormData(formElement));
The server may respond before reading the contents of the files in some condition, and I want to get that response and handle it on the client side.
But it seems that I only get an error event triggered (response with status 0, an empty status text of type json), and 2 readystatechange events with readystate 1 and readystate 4 (same empty response). if the server simply return a response without reading the contents.
I also don't see any response when looking at the POST request in the browser's dev tool (F12->Network tab->Respons)
With curl (curl -i -X POST -H "Content-Type: multipart/form-data" -F "data=blabla" localhost:5000/upload) I'm able to post and get the expected response, but not with XMLHttpRequest.
Any ideas of what I'm doing wrong?

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

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.

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.

Why are POST requests often sent with the Content-type set to urlencoded?

If POST data is sent in the body of a request, why use URL encoding?
POST requests require a contentType to be set to describe the data being sent in the body of the request and url encoding is commonly used.
GET requests do not as there is no body. The request parameters are in the URL.
Here is how this looks in code ( works fine ).
/******************************************************************************/
// AJAX
$P.ajax = function (config_ajax) {
var xhr;
// get
if (config_ajax.type === 'get') {
xhr = new win.XMLHttpRequest();
xhr.open('GET', config_ajax.url, true);
xhr.onload = function () {
if (this.status === 200) {
config_ajax.callback(xhr.responseText);
}
};
xhr.send(null);
}
// post
if (config_ajax.type === 'post') {
xhr = new win.XMLHttpRequest();
xhr.open("POST", config_ajax.url, true);
xhr.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xhr.onload = function () {
if (this.status === 200) {
config_ajax.callback(xhr.responseText);
}
};
xhr.send(config_ajax.data);
}
Here you can see the send data for GET is null and the send data for POST is populated and also that the POST data is url encoded () and the GET data is not.
url encoding is not default as if you do not specify it or some other encoding, an error will be thrown.
I guess, what I'm asking, is why can't I leave it off ( the contentType for POST ) and have the data transfer?
Or if by the specification a Content-type is required. Is there something I can use better than URL encoding.
As stated above, because the data is not in the URL and does not need URL encoding, I would prefer to use something more simple.
My guess is that this is not possible, that this is just a default, that has been used before Ajax, perhaps when POST requests did use the URL?
If POST data is sent in the body of a request, why use URL encoding?
You have to use some sort of encoding.
Most POST requests coming from a browser are submitting form data.
Form data sent in a GET request uses URL encoding.
Using the same encoding means that you can use the same serializer and parser.
I guess, what I'm asking, is why can't I leave it off ( the contentType for POST ) and have the data transfer?
Because you'd be sending some data and not telling the recipient how it should be decoded.
Or if by the specification a Content-type is required. Is there something I can use better than URL encoding.
You can use any encoding you like. URL encoding is convenient and works for most data.
I would prefer to use something more simple
URL Encoding is very simple, and JavaScript makes it easy to generate thanks to encodeURIComponent.

Categories

Resources