converting post API code to get API in nodejs - javascript

I am consuming below API using post. I have another API which I have to consume using get. instead of request.post I used request.get it is giving 401 error. I have to consume another API using GET with basic authentication. anybody can suggest changes for it.
var request = require('request');
var url = 'http://localhost:3000/api/v1/login/'
var user = 'test35';
var pass = 'mypassword';
request.post(
{
uri: url,
form: { username: user, password: pass }
},
function(err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
var json = JSON.parse(body);
console.log('Post successful! Server responded with:', body);
}
);

Does the response of that post request an authentication token (for example an jwt)?
APIs usually return some key that you can use in further requests, for example, in your headers in an get request

Related

Express not accepting post requests after 6 requests

I'm working on a game, i'm trying to get the client to post/put data about the player to the server, but after 6 requests the server seems to crash, then after a minute or so it will accept another 6 requests and repeat. This is the post code:
app.post('/entityData', function(req, res) {
//test = req.body;
//console.log(test);
console.log(req.body);
//entityList[req.params.uid] = req.body;
});
I've got a fair amount of other code but these are all for get requests, which seem to work fine with the client. Here is the code my client is sending:
async function sendPlayerData() {
let playerData = {
num: player.getPos().x
};
console.log(playerData);
try {
let response = await fetch(serverIP + "/entityData", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(playerData)
});
if(!response.ok) {
throw new Error("Error sending player data to server. ");
}
} catch (error) {
console.log(error);
}
}
I get no errors on the client or server, so have absolutely no idea what i'm doing wrong. The only modules i've got on the server is a custom utility module and fs.
The issue was that i was not sending back a response, after i fixed that it worked.

Retrieve redirectUri from npm Request

I'm trying to retrieve some information from the response that npm Request generated. I'm able to retrieve information like "statusCode" by typing "response.statusCode". However if I want to retrieve other information like "redirectUri", it would show undefined. How am I able to retrieve "redirectUri"?
Below is the code to get the response from the URL that I'm testing;
var request = require('request');
var getRequest = function (url, index) {
request(url, function (error, response, body) {
console.log(response.redirectUri);
});
}
getRequest('https://www.exampleUrl.com', 1);
Below are some of the information from the response;
redirects: [
{ statusCode: 302,
redirectUri:'https://www.exampleurl'.....etc
}],
Please see the response in attached image
Note: I have blurred out the url that I'm testing.
I found my answer from How do I get the redirected url from the nodejs request module?. Set "followRedirect: false" and use "response.headers.location".
var url = 'http://www.google.com';
request({ url: url, followRedirect: false }, function (err, res, body) {
console.log(res.headers.location);
});

Spring: request body missing error when sent from client but works with postman?

I have a Spring Rest backend setup as well as a react client. Both are setup on different local ports. I am trying to send a simple request from my React client using a fetch call to my spring rest api.
When sending the POST request using Postman, the API responds as expected.
When sending the request from the React client I receive the following 400 error:
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing: public
org.springframework.http.ResponseEntity<?>
I have done the following:
Disabled CSRF on my spring application.
Set global CORS config to accept all requests.
Ensured on multiple occasions that the request body is correct and identical to that sent via Postman.
Here is my Fetch request from react client:
fetch(API_BASE_URL + '/api/auth/signin', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Request-Method': 'POST'
}),
body: {
username: this.state.uname,
password: this.state.password,
}
}).then(
function (response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function (data) {
let json = JSON.parse(data);
let token = json.tokenType + " " + json.accessToken;
localStorage.setItem(ACCESS_TOKEN, token);
alert('successfully saved token:' + token);
});
}
)
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
For those interested:
The data passed in payload was of an incorrect format. While this may not appear logical, creating a variable as so:
let payload = {
username: this.state.username,
password: this.state.password,
};
And passing that as the body to fetch seems to work.
Hopefully this may help others facing the same problem..

Nodejs Auth0 read users with api not working (err: 400, msg: Bad HTTP authentication header format)

I'm trying to receive my users that are stored in Auth0. So, I tried using this website Auth0 management API docs with my API token and API domain. This works fine!
Then I tried to do the same in node js, but when I do that it returns an error. The error message is:
"statusCode":400,"error":"Bad Request","message":"Bad HTTP authentication header format","errorCode":"Bearer"
This is the code that i fount in the documentation
var request = require("request");
var options = { method: 'GET',
url: 'https://<api_url>/api/v2/users',
headers: { authorization: 'Bearer ACCESS_TOKEN' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The only thing that is changed is that I deleted the query string and inserted my api_url and the same access token that I used on the Auth0 management API docs (which works). Am I missing something?
The code looks perfectly fine. I edited it with my hostname/access token as follows and it returned the users:
var request = require("request");
var token = 'eyJ0...'
var options = { method: 'GET',
url: 'https://tenant_name.auth0.com/api/v2/users',
headers: { authorization: 'Bearer ' + token }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The two things that might have gone wrong in your case are:
You didn't properly replace the ACCESS_TOKEN in the code.
The access token does not have the read:users permission. You can verify this by pasting the token in jwt.io and inspecting the payload.

Chunked base64 string, piece by piece using http nodejs

From my API(nodejs), I'm accessing a third-party API (using http) to download files.
The service returns a Base64 string, chopped into smaller pieces, to be able to handle larger files.
Is it possible to do multiple http-requests (loop ?) to the third-party service, send each piece in response, to the browser until there is no longer any response from the third-party service?
The reason i want to do this, is because I don't want to consume to much memory on the node server.
I will put the pieces back together in the browser.
Any suggestions on how to do this?
See my current code below.
var request = require('request');
router.post('/getfiledata', function(req, res) {
var fileid = req.body.fileid;
var token = req.headers.authorization;
getFileData(req, res, dbconfig, fileid, token, function(err, chunkOfFile) {
if (err) {
res.status(500).send({
status: 500,
message: err
});
return;
}
res.send(chunkOfFile);
});
});
function getFileData(req, res, dbconfig, fileid, token, next) {
var url ="http://*ip*/service/rest/getfiledata";
var reqbody = {
fileId: fileid
};
var options = {
url: url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': token
},
json: true,
body: reqbody
};
/*SOME LOOP HERE TO GET EACH CHUNK AND SEND TO BROWSER*/
request(options, function(err, resp, body) {
if (err) {
console.log(err);
next(err, undefined);
return;
} else {
next(undefined, body)
};
});
};
I think you need Socket.io to push chunks to the browser.
Server :
socket.send("chunk", chunkOfFile)
Client :
let fullString = ""
socket.on("chunk", chunkOfFile => fullString += chunkOfFile )
Something like that
The request library you are using allows for streaming of data from one source to another. Check out the documentation on github.
Here is an example from that page:
request
.get(source)
.on('response', function(response) {
console.log(response.statusCode) // 200
console.log(response.headers['content-type']) // 'image/png'
})
.pipe(request.put(destination))
You may choose to use the http module from Nodejs, as it implements the EventEmitter class too.
I ended up doing a recursive loop from the client. Sending http-requests to my API(node) until the response no longer returns any base64 data chunks.
Thank you guys!

Categories

Resources