Python to Node/JS - javascript

I'm reading a documentation for api but it's example is in python.
Here's the code:
import http.client
conn = http.client.HTTPSConnection("api.sportradar.us")
conn.request("GET", "/mma-t1/schedule.xml?api_key={your_api_key}")
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
But I'm using node. I tried to convert above code to this:
import request from 'request';
const key = Meteor.settings.sportradar.mma_v1;
const conn = `api.sportradar.us/mma-t1/schedule.xml?api_key=${key}`;
request(conn, (err, res, body) => {
console.log('error:', err);
console.log('statusCode:', res && res.statusCode);
console.log('body:', body);
});
but I'm getting an error: Invalid URI.
The response will be in XML if that matters.
Can someone help please?

In node you usually need to append http or https to the uri.

Related

How to use router.get and https.get together? (Node.js)

I want to get information from the http request and send it to the frontend via the path '/ get'. I combined these 2 functions and it works but I don't think it is correct:
const router = express.Router();
const https = require('https');
router.get('/get', (req, res) => {
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
res.json(JSON.parse(data).explanation)
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
});
Is there a better way to do this?
The better way would be to use Axios to make all your http requests to external apis which you want from nodejs application. It is a promise based request making library which you can use in browser as well as on backend server.
Install axios using npm install axios
axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY').then(response => res.send(response.data)).catch(error => console.log(error));
No, it works fine.
But if you want another way, then use axios
you need to require axios and then add your request in the router.
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
you get more information from here

How do I do a GET for Firebase.functions().httpsCallable?

How do I do a GET for Firebase.functions().httpsCallable?
I keep receiving a POST error 404 but this is a GET request to my server. Should I pass in nothing or there is something to change this httpsCallable to get function?
Client
let updateWorkshop = Firebase.functions().httpsCallable('api/update/workshop');
updateWorkshop({/* nothing */})
.then(res => {
console.log(res);
}, err => {
console.log(err);
})
Server
app.get('/v3/update/workshop', asyncMiddleware( async (req, res, next) => {
let results = await UPDATE_WORKSHOP_DATE.Run()
res.status(200).json({results: results})
}))
exports.api = FUNCTIONS.https.onRequest(app);
If you are just trying to ping your callable function endpoint, a GET won't work. As you can see from the protocol specification for callable functions, it uses a POST. If you use a GET, it's an error because you're not following the protocol.

Why Does My NodeJS Code Throw: ECONNRESET error?

My program parses a text document with HTTPS proxies in a string array. It then makes a GET request to ipify.org.
However, my program is throwing: Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:183:27). It terminates my program instead of throwing an error and continuing.
My code:
var fs = require('fs');
var async = require("async");
var request = require("request");
var proxies = fs.readFileSync(__dirname + '\\proxies.txt').toString().split("\n");
console.log(proxies.length + ' proxies loaded!');
async.forEachOf(proxies, proxy => {
request({
'url':'https://api.ipify.org',
'method': "GET",
'proxy': 'http://' + proxy
},function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else {
console.log(error.message);
}
})
}, err => {
console.log(err.message);
});
Any help is highly appreciated :)
[Node js ECONNRESET
the error is explained here.I think the url is not being connected for some reason...

Upload image using Node js and electron. (convert from c# code)

I'm converting an application from c# to electron and i have some problems when i try to make a request to upload an image on a server (not my server).
For c# i used RestSharp library and all worked fine.
private void UploadImage(string id)
{
RestClient client = new RestClient("https://www.website.com")
{
CookieContainer = new CookieContainer()
};
string path = #"D:\Downloads\image.jpg";
var request = new RestRequest("/upload?id=" + id, Method.POST);
request.AddFile("myfile", File.ReadAllBytes(path), Path.GetFileName(path), "image/jpeg");
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
client.Execute(request);
}
How can i convert this code in Node js? The only thing i could found was code that uploaded to their own server and that does not work for me.
This is what i tried in Node js
var fs = require('fs');
var request = require('request');
fs.createReadStream("D:\Downloads\image.jpg").pipe(request.post("https://www.website.com/upload?id=" + productId, function (error, response, body) {
if (error) {
console.log(error);
} else {
console.log(response);
}
}));
Using the code above i get status code 200 and the body response is telling me that no image was select. So the request is working, but sending the image doesn't.
This is what i did in order to solve the problem. Maybe it will help somebody else too.
var fs = require('fs');
var request = require('request');
var req = request.post(uploadURL, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('myfile', fs.createReadStream("path\to\image.jpg"), {
filename: "image.jpg",
contentType: 'image/jpeg'
});
I've been trying to use the same technique using Electron to upload files to my localhost test server, but no luck. My code returns as successful in the console, but no file is ever uploaded. Is this something you came across, or is there anything you may be able to see I'm doing differently?
const fs = require('fs');
const request = require('request');
var uploadURL = 'http://localhost:80/sandbox/img';
var req = request.post(uploadURL, function (err, resp, body) {
if (err) {
console.log(err);
} else {
console.log(body);
}
});
var form = req.form();
form.append('upload', fs.createReadStream("C:/nodejs/dave/assets/img/brand_logos/logo.jpg"), {
filename: "logo.jpg",
contentType: 'image/jpeg'
});
Below is the response I get, which I'm assuming is expected...
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved here.</p>
<hr>
<address>Apache/2.4.27 (Win64) PHP/7.0.23 Server at localhost Port 80</address>
</body></html>

How to get parameters of `req` in express node server

I have two paramaters in my UI. One is a file and another is dataObject. In the utils, I have written code as :
importPlan: function (formData, planDTO) {
return axios.post(`${importPlanAPIPath}`, planDTO, formData);
}
In the router, I am sending this as :
router.post('/plans/importPlan/', planController.importPlan);
and in the controller, I have written the request as :
async importPlan(req, res, cb) {
let plan,
planDTO = req.body;
const formData = new FormData(),
file = req.files.file;
formData.append('file', file.data);
console.log('planDTO => ', planDTO);
console.log(file.data, file.name);
try {
plan = await req.clients.planClient.importPlan(formData, planDTO);
} catch (err) {
return cb(err);
}
res.json(plan);
}
In the req.body, I am getting the planDTO but I am not getting any req.files in the req. Also I am using bodyparser to parse the request. I am also using busboybodyparser for multipart/form-data.
Can Somebody please tell what I am doing wrong?
Thanks in advance.
yourparam is parameter name
router.post('/plans/importPlan/:yourparam', planController.importPlan);
async importPlan(req, res, cb) {
var yourparam= req.params.yourparam;
..........
res.json(plan);
}
use this module for file upload https://www.npmjs.com/package/multer

Categories