read CSV coming from rest-api in Angular-8 - javascript

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.

Related

using http with axios return 400 with request it works

I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.

Store session from initial login via POST?

I am running nodeJS and have the following function:
const fetch = require("node-fetch");
async function createCustomer() {
let response = await fetch('https://sampleurl.com/login', {
method: 'POST',
body: 'username=usernameHere&password=passwordHere',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar = await response.json();
console.log(tempVar);
This logs in and authenticates, providing me a successful response.
However if I then try and do the next step, it fails with an unauthorized error.
let response2 = await fetch('https://sampleurl.com/list', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar2 = await response2.json();
console.log(tempVar2);
In python I use requests.Session() and do the initial authorization and then any API call after that just begins with 'session' and it works. For example::
session = requests.Session()
session.post('https://sampleurl.com/login',data={'username':'usernameHere','password':'passwordHere'})
response = session.get('https://sampleurl.com/list').json()
print(response)
This is the functionality I am trying to replicate, but I can't figure out how to store the session.
Any help would be much appreciated.
Edit: Using Express.
Edit2: This is not hitting an API I am running the server for, I am not looking for how to build this feature as the API server, rather just connect to an external API.

How do you make an API request using browser fetch with token auth

I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})

Fetching data using Angular 5 HttpClient

I am trying to load data from a rest endpoint using the HttpClient provided by Angular. The endpoint in question uses a token to authorize the user.
getData() {
if (this.token) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + this.token
})
};
this.http.get('https://some url', httpOptions).subscribe((res) => {
console.log(res);
}, (error) => {
console.log(error);
});
} else {
this.empty_token = true;
}
}
I get the following error while trying to do that:
Response for preflight has invalid HTTP status code 401.
However, the same code works for a some demo url that works on "http" and not for "https".
I tried using the same by making a request using Postman or any other RestClient for that matter and it works fine.
If the calling url is http it is normal that it does not work.
This could help you https://angular.io/api/platform-browser/DomSanitizer
Or try this
private httpOptions = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.token});
you should add
"proxies": [
{
"path": "/v1",
"proxyUrl": "'https://some url'"
}
to your project .
you can look to this link https://github.com/mgechev/angular-seed/wiki/Add-a-Proxy-to-browsersync

Fetch response malformed

The issue is basically that the fetch response object is not correct. Pictures to clarify the issue are below as it is hard to explain.
My fetch request code.
fetch(this.constructUrl(url), {
method: method,
mode: 'no-cors',
headers: new Headers({
'Authorization': 'Bearer ' + this.token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}),
body: new FormData(document.getElementById(formIdentifier))
}).then(function (response) {
if (response.ok) {
return response.json().then(callback);
}
console.log(response);
}).catch(function(error) {
console.log(error);
});
The fetch response object.
The chrome response/request details
The chrome response data
So as you can see, the data in chrome looks correct but for some reason, the fetch response object does not seem to reflect what chrome picks up.
I had to switch 'no-cors' to 'cors' and allow cors in my rest stack.

Categories

Resources