request.get vs CURL in NodeJS - node.js

I have an URL mapped as
router.route('/user').get(policies.isAuthenticated, policies.isCurrentUser, userController.get);
When I access the URL with CURL or from the browser it runs through all of the chained methods. But when I access it from NodeJS it only runs the last method, userController.get. I'm using the following request method.
request.get({
url: testURL,
body: user.id,
json: true
}, function(err, res: express.Request) { ... });
Do I need to include some options in request.get so that it acts like a 'proper' request?

Related

Body of a request is empty [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

nodeJS request library: making POST request with surrogate key instead of URL

I am trying to use nodeJS request library to issue a POST request to purge content associated with a certain surrogate key via Fastly API. The POST request would look something like this:
POST /service/SU1Z0isxPaozGVKXdv0eY/purge
Content-Type: application/json
Accept: application/json
Fastly-Key: YOUR_FASTLY_TOKEN
Fastly-Soft-Purge: 1
Surrogate-Key: key_1 key_2 key_3
I tried to do this in node.JS two different ways.
The first:
// perform request to purge
request({
method: `POST`,
url: `/service/${fastly_service_id}/purge${surrogateKeyArray[i]}`,
headers: headers,
}, function(err, response, body) {
// url was not valid to purge
if (err) {
console.log("is there an err???")
console.log(err)
}
})
}
I get, Error: Invalid URI: /service/<fastly_Service_id>/purge/<surrogate_key>
I double checked my surrogate key via curl -s -I -H "Fastly-Debug: 1" <URL corresponding to surrogate key> | grep surrogate-key
And it returns the same surrogate-key used in my code.
In the second attempt, I tried:
// perform request to purge
request({
method: `POST /service/${fastly_service_id}/purge${surrogateKeyArray[i]}`,
headers: headers,
}, function(err, response, body) {
// url was not valid to purge
if (err) {
console.log("is there an err???")
console.log(err)
}
})
}
I get the error, Error: options.uri is a required argument
I'm unfamiliar with node and the code involved to make a HTTP request successfully, but from what I can see of the code you have provided it would appear the error is related to the fact you've not provided a fully qualified domain (e.g. you're missing https://api.fastly.com before the path).
Unless of course this is configured elsewhere in your code and it's just not visible here.
Also make sure that inbetween /purge and ${surrogateKeyArray[i]} you include a / divider (I show this in my example code below).
So with this in mind I would suggest trying:
request({
method: `POST`,
url: `https://api.fastly.com/service/${fastly_service_id}/purge/${surrogateKeyArray[i]}`,
headers: headers,
}, function(err, response, body) {
if (err) {
console.log(err)
}
})
}

make a GET request in node js equivalent to CURL request with -u parameter

i am trying to make a GET request to an external api from node js and express js.
I am using the request module to make the GET request-
in the options of the request -
const options = {
url: 'https://externalP_api_url/api/1/balance',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
I need to set the -u parameter as based on the example in the docs of the api. they used curl to make the request
curl -u keyid:keysecret https://externalP_api_url/api/1/balance
The problem is i cant set the -u keyid:keysecret in the options of my request i have tried putting it like a query string and in the header but i get a 401 and accoring to the api's docs that means the keyid:keysecret parameter is missing.
I have tried the curl and it works so i knw its not from the api's end and its not cause i am not sending from an https doamain because i would have a gotten a 403 response.
Take a look at https://curl.trillworks.com/#node
It typically does a pretty good job of pointing you in the right direction when converting curl to node.js. Based on your curl command, it is suggesting the following code:
var request = require('request');
var options = {
url: 'https://externalP_api_url/api/1/balance',
auth: {
'user': 'keyid',
'pass': 'keysecret'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);

Request multiple url for web scraping

I have this simple script:
request ({
method: 'GET',
url: 'https://www.link1.org/'
url: 'https://link2.net/'
}, function(err, response, body) {
//do stuff
}
It works fine with single url but how could i add another? I need it to get both urls.

api call fails with request module in node.js app

The following API call fails for me when I try it in my app. It works fine from same machine in the browser. I should get a JSON response.
var url = 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC';
request.get({ url: url, json: json, strictSSL: false, headers: { 'User-Agent' : '' } }, function (err, resp, data) {
});
edit: by "fails" i mean i get a non-json error page.
You can't use an empty User-Agent header, otherwise the request fails.
So use something like:
'User-Agent' : 'request/x.y'

Resources