How to run terminal commands using Dart HttpRequest? - dart

I need to send a request to the server to run a jar file with a string argument/parameter and return the results as a string.

On server side you can run a process and send result back like this :
HttpServer.bind(InternetAddress.ANY_IP_V4, 3031).then((server) {
server.listen((HttpRequest request) {
var param = request.uri.queryParameters['name'];
Process.run('java', ['-jar', 'myJar.jar', param]).then((pr) =>
request.response
..write(pr.stdout)
..close()
);
});
});

Related

Enabling Google Cloud Run chunked encoding

I have tried returning 'transfer-encoding:chunked' header to a large download but the response terminated at "31.9M" which is very close to the documented "32MB" limit.
The Unofficial FAQ states chunked encoding is now possible, but I can't seem to get it working.
Do I have to flip any flags (e.g. https/2) to enable streaming? Is it only possible in some regions? (I am using europe-west1)
The following minimal case does actually stream 45MB over Cloud Run, without any special configuration, confirmed in us-central1 and europe-west1
FROM node:14-slim
COPY index.js index.js
CMD [ "node", "index.js" ]
const http = require('http');
http.createServer((request, response) => {
response.setHeader('Transfer-Encoding', 'chunked');
// 45MB
var i = 1000000;
function nextChunk() {
return new Promise(resolve => {
if (i-- > 0) {
response.write(
'123456781234567812345678123456781234567812345678',
() => nextChunk()
);
} else {
response.end();
}
})
};
Promise.all(nextChunk())
}).listen(process.env.PORT || 8080);
Even after straming into chunks I'm always getting error after 32 MB reponse size, I can't get the response header 'Transfer-Encoding' = 'chunked' from Cloud Run service response :
I'm using NestJs, and I can get it in the response Headers when I execute the app locally.
I'm specifying it as :
#Get('streamable')
#Header('Transfer-Encoding', 'chunked')
async streamable(#Res() res) { etc.. res.write(chunk)}

Can I can return json list from HttpClientResponse

I am trying to connect with our server using dart and flutter. I get an error in certificate server, I get the code and I get response exactly, but the problem is the response keeps coming back as a string. I want it as a list to loop through it.
HttpClient client = new HttpClient();
client.badCertificateCallback =((X509Certificate cert, String host, int port) => true);
String url ='https://xxx';
//Map map = { "email" : "email" , "password" : "password"};
HttpClientRequest request = await client.getUrl(Uri.parse(url));
//request.headers.set('content-type', 'application/json');
//request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
I have simple code to get a JSON response as a list. The problem is our server is using https and nginx to take all request to the correct port. Previous code worked but I need to respond with a list.
simple code is :
String apiURL = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(apiURL);
return json.decode(response.body);
You won't get a list. You would get flat json which you would need to process. Processing can be done using simple script using powershell.

How to capture responsebody from newman

I want to capture the responsebody in Newman.
const newman = require('newman');
newman.run({
collection: require('./xxx.json'),
iterationData: './data.jsp',
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('collection run complete!');
console.log(summary);
});
I use the code above. it works fine but I want to capture the json output here from the call. How can I achieve it?
Perhaps you used a wrong term for retrieving json response body. If you want to just get the response body you need to parse JSON returned and to save it to a variable.
If you would use newman to run through command line there are everything is super simple:
let body = JSON.parse(responseBody)
console.log(body)
and after test where you need to see the response you put this 2 lines of code.
But with your case perhaps you need that:
1) Callback option
const newman = require('newman');
newman.run({
collection: require('./xxx.json'),
iterationData: './data.jsp',
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('collection run complete!');
console.log(summary);
})
.on('request', function (err, data) {
// err, data can be used to write to files using the node fs module.
});
or the better and modern option:
let response = await newman.run({
collection: 'collection',
environment: 'env',
})
.on('request', async function (err, data) {
// err, data can be used to write to files using the node fs module.
});
console.log(response)
Not sure I will be working as expected, but at least try.
Btw, where do you run these tests? just in clear env or use some runner framework.
Postman return execution summary in Callback function. after execution if you save the summary in callback and return it. you can access request/response/ headers.
function runcollection(callback){
newman.run({
collection: 'C:\\newman\\PMP Dependency latest collection\\Updated\\TestCollection.postman_collection.json',
environment: 'C:\\newman\\PMP Dependency latest collection\\Updated\\Test.postman_environment.json',
iterationCount :1
},function(error, summary){
callback(summary)
});
}
runcollection(result => {console.log(result.run.executions[0].response.stream.toString())});

In dart httpRequest getstring always error

I established a RESTful server, and I can get a simple string with my Chrome or IE using this URL: "http://localhost:8080/WebService/RESTful/getString"
But when using Dart, it always returns a error message:
"[object XMLHttpRequestProgressEvent]"
From the onError() callback method,
I'm sure that server returns a string with "text/plain" MIME type in Java.
Here is the code:
import 'dart:html';
void main() {
HtmlElement btn = document.body.querySelector("#btn");
btn.onClick.listen(onClick);
}
void onClick(Event v) {
var url = "http://localhost:8080/WebService/RESTful/getString";
HttpRequest.getString(url).then((str) {
window.alert(str.toString());
}, onError: (e) {
window.alert(e);
});
}
Who can help me ?
If you try to fetch resources from another server than the one your page was loaded from, this server needs to return CORS headers otherwise your browser refuses to fetch form this other server.
It depends on your server how this can be configured or added.
See for example
- How do you add CORS headers in Redstone interceptor?
- CORS with Dart, how do I get it to work?

Meteor - Parse Data from Incoming HTTP Request

For outgoing HTTP requests (using meteor.http.call) I can define params and/or data. The results are then available (via results.content).
How do I access and parse the body/contents/data of incoming HTTP requests?
Using iron-router, I have got as far as this:
Router.map(function () {
this.route('httpTest', {
path: '/httpTest',
action: function () {
var request = this.request;
var response = this.response;
console.log('request_body: '+ request.body);
// request.body does not work. what should it be????
N.B. I understand that I CAN access query parameters, but I want to access form data and/or json data from the body of an incoming http request.
The request is an incoming http message, which is a Readable Stream, so you can get the data of the request by reading from that stream.
The following should work (but I haven't tested it):
var readable = this.request;
var alldata = "";
readable.on('data', function(chunk) {
alldata += chunk;
})
readable.on('end', function() {
console.log('do something with alldata');
});
It may not be working because of the missing where: 'server'. Here is a working example:
Router.map(function() {
this.route('test', {
where: 'server',
action: function() {
console.log(this.request.body.make);
console.log(this.request.body.model);
this.response.writeHead(200, {'Content-Type': 'text/html'});
this.response.end('hello!\n');
}
});
});
From the command line I can hit this route with:
curl -X POST -H "Content-Type: application/json" -d '{"make":"honda","model":"civic"}' http://localhost:3000/test
Which prints the expected honda and civic in the server's terminal. It looks like this.request.body is already parsed so you can access any variables directly which is nice if your input is json.
To read the raw body, without having Node.js JSON-ify it, in a synchronous way, I used this:
Router.route("my/api", function() {
var rawBody = "";
var chunk;
while ((chunk = this.request.read()) !== null) {
rawBody += chunk;
}
}, { where: "server" });
(the asynch way proposed in another answer here didn't worked for me, although it should as per Node.js documentation).

Resources