Is it possible to combine a GET and POST in Javascript? - json

I have javascript code that should login (ie send some information to the server) and then receive a reply JSON message. I know this is doable by first doing a post, and then in the asynchronous response, when it completes, do a get. This would require two callback functions and two messages.
I was just wondering whether there is any way to do a get and send JSON as part of the query, so that there is just a single request/response rather than two.
Here is a sample post I wrote:
function post(url, payload, callback) {
payload = JSON.stringify(payload);
var http = new XMLHttpRequest();
http.open("POST", location.pathname + url, true);
http.setRequestHeader("Content-type", "application/json");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status !== 200) {
callback(false, http.response);
} else if (http.readyState === 4 && http.status === 200) {
callback(true, http.response);
}
return;
};
http.send(payload);
}
If I want to get back JSON, what do I do?
Is it as simple as changing POST to GET and looking at:
http.responseText upon the return?

If you are doing any login functionality you should always use the HTTP POST method.
You could use AJAX (W3schools documentation about AJAX ) to handle sending your login form over POST and then handle the response in the same code block. bellow is an example.
$('#login-form').submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
// serializes the form data with id login-form
var formData = $(this).serialize();
$.ajax({
type: 'POST',
data: formData,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
url: $(this).attr('action'),
//if your server sends a status OK message handle the response
//data will be the JSON response from the server
success: function(result,status,xhr) {
var jsonRes = JSON.parse(result); // parse the JSON object
console.log(jsonRes);
},
//if there was an error with your request the server will send
// an error response code and it is handled here
error: function(xhr,status,error) {
console.log(error);
}
});

Related

How to get a value from returned JSON in HTML?

My client side looks like this:
filename="random_filename.docx"
var response = await fetch("https://backend.wl.r.appspot.com/scriptstuff", {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ file: filename })
});
var data = response.json();
console.log(data);
and my backend return looks like this
response = jsonify({'prediction': str(prob)})
response.headers['Access-Control-Allow-Origin'] = '*'
return response, 200
I receive a promise with the value of 'prediction', but I'm not sure how to access that or why the current code isn't working.
EDIT: adding await before response.json() works
You can execute a function upon a promise being fulfilled by appending a .then() to the fetch request. If you're already receiving the JSON object then the values can be accessed by data.some_key.
I'm not an expert but first store str(prob) into a variable and then create an object with it. I think jsonify() takes things very literally.

Get json with headers by using nodejs

How can I get objects from JSON with headers and send an HTTP get a request to a link?
setHeader('header1', 'header1_value') for http://getsomejson.com/json.php
and retrieve data then send them to
randomlinktosenddata.com
You could use a library like request
try this code:
var request = require('request');
var options = {
url: 'http://getsomejson.com/json.php ',
headers: {
'Some-header': 'header-value'
}
};
request(options, (error, response, body) => {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
// use data
request({url:'randomlinktosenddata.com'} , (error,response,body) => {
// do more stuff...
});
}
});
you can install the request library by doing npm install request
Check this link: https://github.com/request/request
hope this helps

I'm not using Express, but I'm trying extract POST data then to send a json as response, with no luck

I'm still very new to node.js so please bear with me.
I'm trying to extract POST data then sent a json as response, but I don't seem to be able to extract the data from the POST request and even worse I can't find the syntax for people who are NOT using Express to send the json. It keeps telling me res.json is not a function.
EDIT: I found out the problem for the json part, I was a dump. I finally remember what I was told, json are sent like strings.
var http = require('http');
var qs = require("querystring");
server = http.createServer(function (req, res) {
try {
var body = "";
var post = qs.parse("");
if (req.method == "POST") {
res.writeHeader(200, {"Content-Type": "application/json"});
req.on("data", function (data) {
body += data;
console.log(data); //It gives something like <Buffer xx xx xx ...>
if (body.length > 1e6)
req.connection.destroy();
});
req.on("end", function () {
post = qs.parse(body);
console.log(post.test); //It gives "undefined"
});
res.end(JSON.stringify({ a: 1 }));
} catch(err) {
console.dir(err);
res.writeHeader(200, {"Content-Type": "text/plain"});
res.end("Hi hi");
}
});
server.listen(8000);
console.log("http start #8000");
Any help? Thanks in advance.
below solves the date to string (i.e. converting buffer to string
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// console.log(textChunk); // will give you a stream of text from data
});
you could store textChunk out of the ondata handler, to then use that if required (say returning relevant data to the user back again)

frisby and read the response header with json response REST API

I am using frisby to automate the REST API testing. All of my REST API is based on json and return json response. In one of the requirement, I need to read the response header and fetch the response header and set it for next request. With json response, I am not able to read the response header. Following is sample code for my test.
frisby.create("Check to make sure that user does exist")
.get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
.expectHeaderContains('content-type', 'application/json')
.afterJSON(function (response) {
//How to read session id from header
//var sessionId = res.headers[constants.SESSION_ID_HEADER_KEY];
var exist = response.exist;
expect(exist).toBe(true);
});
Please help.
You code was actually OK, you were just trying to use 'res' variable instead of response.
frisby.create("Check to make sure that user does exist")
.get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
.expectHeaderContains('content-type', 'application/json')
.afterJSON(function (response) {
var sessionId = response.headers[constants.SESSION_ID_HEADER_KEY];
// Use the sessionId in other frisby.create(...) call
}).
toss();
Another alternative is to use after() as follows:
frisby.create("Check to make sure that user does exist")
.get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
.expectHeaderContains('content-type', 'application/json')
.after(function (err, res, body) {
var obj = JSON.parse(body);
var sessionId = obj.headers[constants.SESSION_ID_HEADER_KEY];
// Use the sessionId in other frisby.create(...) call
}).
toss();

Reading data from res.end()

I'm sending a simple data back from the server to the client.
app.post('/user', function (req, res) {
var userName = "John";
res.end(JSON.stringify({"error":"", "user": userName}));
});
$.ajax({
type: "POST",
...
contentType : 'application/json',
dataType: "json"
})
.done(function(data) {
// send join message
var resData = JSON.parse(data);
alert("hello"); // this doesn't show up
});
});
});
But in the browser console, I get this error - "Uncaught SyntaxError: Unexpected token o".
If I do JSON.stringify and JSON.parse on the content, it works fine.
alert(JSON.parse (JSON.stringify({"error":"", "user": userName})).user);
And also, .done works fine without a data payload from the server i.e. the alert("hello") works.
So, I'm guessing something fishy is happening while sending data within res.end(). Please help.
While at it, it would be nice if you can also tell me how to do the same using res.json() and which one is preferable.
The problem here is that you set dataType: 'json' in your jQuery request. This causes the response from the server to be automatically parsed as JSON, so it will return the object rather than the raw server response.