I'm trying to stream price data via HTTP (Don't know why they don't use websockets..) and I use axios to make normal REST API requests but I don't know how to handle 'Transfer Encoding': 'chunked' type of requests.
This code just hangs and doesn't produce any error so assume it's working but not able to process the response:
const { data } = await axios.get(`https://stream.example.com`, {headers:
{Authorization: `Bearer ${token}`, 'Content-Type': 'application/octet-
stream'}})
console.log(data) // execution hangs before reaching here
Appreciate your help.
WORKING SOLUTION:
As pointed out from the answer below, we need to add a responseType: stream as an axios option and also add an event listener on the response.
Working code:
const response = await axios.get(`https://stream.example.com`, {
headers: {Authorization: `Bearer ${token}`},
responseType: 'stream'
});
const stream = response.data
stream.on('data', data => {
data = data.toString()
console.log(data)
})
FYI, sending the content-type header for a GET request is meaningless. The content-type header applies to the BODY of the http request and there is no body for a GET request.
With the axios() library, if you want to get direct access to the response stream, you use the responseType option to tell Axios that you want access to the raw response stream:
const response = await axios.get('https://stream.example.com', {
headers: {Authorization: `Bearer ${token}`,
responseType: 'stream'
});
const stream = response.data;
stream.on('data', data => {
console.log(data);
});
stream.on('end', () => {
console.log("stream done");
});
Axios document reference here.
Related
I am trying to make some modifications to my Rest API by making the PUT request using request package but it does not seem to work so. Although I am able to make the modifications to the same API using the same JSON body using the Postman. Also, I am not getting any errors so not understanding what's wrong.
Since request was not working, I tried axios even with that no response no error. Following is my sample code which is making request to my Rest API:
const request = require('request');
const axios = require('axios');
const https = require('https');
request(
{
url: testIdUrl,
method: 'PUT',
agentOptions: {
rejectUnauthorized: false
},
headers: [{
'content-type': 'application/json',
body: JSON.stringify(requestBody)
}]
},
function(error, response, body) {
if(error){
console.log("SOMETHING WENT WRONG")
console.log(error)
}
console.log("RESPONSE FROM TEST ID PUT")
})
axios.put(testIdUrl, requestBody)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
}).catch((err) => {
console.error(err);
});
Can someone please help me understand what's wrong with the code? Does my Rest API include all the tokens and information? When I use the same requestBody and URL then its works in POSTMAN.
I have a rest-api which is returning csv file, how can i get it in the angular service.
getCSV() {
let headers_object = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer "+ "7woNSuuEYqLfQAuqwHhCJn8aq2SM"
});
const httpOptions = {
headers: headers_object,
Accept: 'text/csv'
};
this._http.get(
'https://00.00.xx.00:9001/abcd/export', httpOptions
).subscribe(resp => {
console.log(resp)
}
);
}
Data is coming in network tab, but angular goes into the ERROR status saying http failure during parsing for because somehow it is expecting the json return.
Please help
Headers in POSTMAN as attached in image.
I have a React project that I run with npm start and this code gets 401 Error from the second fetch (the first one is ok). It runs fine returning 200 only with node, like in "node App.js".
So what would I need to do to run my React project getting 200 response? Why is there this difference between npm and node to this request response?
const clientID = <ClientID>
const clientSecret = <ClientSecret>
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${encode}`,
},
};
fetch("https://auth-nato.auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials", requestOptions)
.then(response => { return response.json() })
.then(data => {
const requestOptions2 = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json',
'Authorization': `Bearer ${data.access_token}`
},
body: '{"username":"Ana", "password":"test123","user_id":"ana#email.com"}'
};
fetch('https://j1r07lanr6.execute-api.sa-east-1.amazonaws.com/v1/register', requestOptions2)
.then(response => {console.log(response)});
})
Buffer - is not presented in the browser's javascript.
Instead of
const encode = Buffer.from(`${clientID}:${clientSecret}`, 'utf8').toString('base64')
use just
const encode = btoa(`${clientID}:${clientSecret}`);
Read more about base64 encoding on MDN.
I found out it was a CORS issue that needed to be set correctly on the back-end. My workaround was disabling chrome web security and removing "mode: no-cors".
I've tried adding "Access-Control-Allow-Origin":"http://localhost:3000" to headers but it doesn't work.
I am trying to upload a file from a react front end to a C# backend. I am using drop zone to get the file and then I call an api helper to post the file but I am getting different errors when I try different things. I am unsure exactly what the headers should be and exactly what I should send but I get two distinct errors. If I do not set the content-type I get 415 (Unsupported Media Type) error. If I do specify content type as multipart/form-data I get a 500 internal server error. I get the same error when the content-type is application/json. The url is being past in and I am certain it is correct. I am unsure if the file should be appended as file[0][0] as I have done or as file[0] as it is an array but I believe it should be the first. Any suggestions welcome :) Here is my api post helper code:
export const uploadAdminFile = (file, path, method = 'POST', resource =
config.defaultResource) => {
const url = createUrl(resource, path);
const data = new FormData();
data.append('file', file[0][0]);
data.append('filename', file[0][0].name);
const request = accessToken =>
fetch(
url,
{
method,
mode: 'cors',
withCredentials: true,
processData: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json', //'multipart/form-data',
Authorization: `Bearer ${accessToken}`,
},
body: data,
})
.then(res => res.json())
.then(success => console.log('API HELPER: file upload success: ', success)
.catch(err => console.log('API HELPER: error during file upload: ', err)));
return sendRequest(request, resource);
};
Thanks for the help and suggestions, it turned out to be a backend issue but even still I learned a lot in the process. I will post my working code here in case anyone comes across this and finds it useful.
export const uploadAdminFile = (file, path, resource=config.defaultResource) => {
const url = createUrl(resource, path);
const formData = new FormData();
formData.append('file', file[0][0]);
formData.append('filename', file[0][0].name);
const request = accessToken =>
fetch(url,
{
method: 'POST',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: formData,
});
return sendRequest(request, resource);
};
As mentioned, the file name does not need to be sent separately and count be omitted. I am indexing the file this way because I get it from dropzone as an array and I only want a single file (the first one in the array). I hope this helps someone else out and here is a link to the mdn fetch docs (good information) and a good article on using fetch and formData.
I'm sending data in my React component via the Fetch API, and returning the result as JSON. When POSTED on my Express server, I use the jsonParser method from bodyParser to parse through the data, but insead I'm only getting back a empty object. I do not understand what's the issue with jsonParser, because if I use textParser, my data get sent fine.
Edit: When printing out the request (req) on the server, it is showing that nothing was received in the body. This only happens with jsonParser though, and not textParser.
Fetch:
fetch('./test',{
method: 'POST',
body: ["{'name':'Justin'}"]
})
.then((result) => {
return result.json();
})
.then((response) => {
console.log(response);
})
.catch(function(error){
//window.location = "./logout";
console.log(error);
});
Express:
app.use('/test', jsonParser, (req,res) =>{
res.json(req.body);
})
Assuming you want to post the {name: 'Justin'} object, you'll want something like
fetch('test', {
method: 'POST',
body: JSON.stringify({name: 'Justin'}),
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8'
})
})
The body parameter does not accept an array (which is what you were passing).
If you did mean to post an array, simply change the body value to
JSON.stringify([{name: 'Justin'}])