Sending header parameters in angular2 and reading them from node - angularjs

In my application I'm trying to send some header parameters from the angular2 application to my node server:
var token = localStorage.getItem('token');
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Auth-Token', token);
var url = this.baseUrl + '/initdata';
return this._http.get( url, {headers: headers, body : {}}).toPromise()
.then(response => {
const status = response.json().status;
if(status == SERVER_RESPONSE_STATUS.SUCCESS)
{
return response.json().result;
}
else if( status == SERVER_RESPONSE_STATUS.FAILED)
{
throw new Error(response.json().message);
}
})
.catch(this.handleError);
}
But the problem is when I'm trying to read the value from node, the value for "auth-token" cannot be extracted (saying undefined)
router.use('/', function (req, res, next) {
tokenGenerator.verify(req.header('auth-token'), Constants.AUTH_PRIVATE_KEY, function (err, decoded) {
});
});
in angular2, I'm importing Headers from http as well:
import {Http, Headers} from "#angular/http";
Can someone please help me what's the issue here?
Thanks

You can read tokens from header like this
if(req.headers.hasOwnProperty('token')) {
req.headers.authorization = 'Bearer ' + req.headers.token;
token = req.headers.token;
}
To send the token from Ng2
headers.append('token', token);
This us how I do it.

Related

React Fetch download a pdf from Java REST API won't read in Adobe

I have tested the API in Postman and the PDF renders fine. So I know the API is working correctly.
When I fetch the PDF from within my React code Adobe gives me the error: "Adobe Acrobat cannot open the because it is neither a supported file type or because the file has been damaged"
My React code:
const downloadFile = async uploadId => {
const response = await callFetch("/uploads/download/" + uploadId + "?officerId=" + officerId, "GET", "");
if (response.status === 401 || response.status === 403) {
alert("Error " + response.status);
sessionStorage.clear();
return;
}
const file = response.blob();
const url = URL.createObjectURL(
new Blob([file], {type:"application/pdf"})
);
const link = document.createElement('a');
link.href = url;
link.setAttribute(
'download',
`FileName.pdf`,
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
link.parentNode.removeChild(link);
URL.revokeObjectURL(url);
};
const callFetch = (endpoint, method, jsonStr) => {
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Accept","application/json");
return callFetchApi(endpoint, method, jsonStr, myHeaders);
};
const callFetchApi = (endpoint, method, data, myHeaders) => {
const serverName = "http://localhost:8080/AuxPolice/api";
myHeaders.append("Access-Control-Allow-Credentials", 'true');
myHeaders.append("Access-Control-Allow-Origin", '*');
const jwt = sessionStorage.getItem("jwt");
let headerJwt = "Bearer " + jwt;
if (jwt != null) {
myHeaders.append("Authorization", headerJwt);
}
let myInit = {method: method
,headers: myHeaders
};
let url = serverName + endpoint;
if (data) {
myInit.body = data;
}
let returnFetch = fetch(url, myInit);
return returnFetch;
};
Here is my Java code:
#GetMapping(value = "/download" + "/{id}")
public ResponseEntity<Resource> downloadGet(#PathVariable Long id, #RequestParam Long officerId) throws SQLException
{
Officer loggedInOfficer = this.auxPoliceService.getOfficer(officerId);
Upload paramRec = new Upload();
paramRec.setUploadId(id);
Upload download = auxPoliceService.getUploads(loggedInOfficer.getOfficerId(), paramRec).get(0);
Blob blob = download.getBlob();
byte [] bytes = blob.getBytes(1, (int)blob.length());
blob.free();
InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bytes));
String filename = download.getFilename();
String contentType = "application/pdf; name=\"" + filename() + "\"";
HttpHeaders headers = new HttpHeaders();
headers.set("content-disposition", "inline; filename=" + filename);
return ResponseEntity.ok()
.headers(headers)
.contentLength(bytes.length)
.contentType(MediaType.parseMediaType(contentType))
.body(resource);
}
Any ideas?

React Django CSRF token missing or incorrect

In action file the code:
...
const config = {
headers:{
'Content-type': 'application/json'
}
}
const {data} = await axios.post('http://localhost:8000/api/register/',
{'email':email, 'password':password}, config)
...
It's working; then localhost:8000 moved to package.json as a proxy, after that got an issue CSRF token missing or incorrect, how to fix that, thanks.
Application was restarted with no changes. Furthermore, the request has changed to localhost:3000 instead of 8000.
Django can provide the CSRF token in your cookies with a decorator. Then you can get it from your cookies and add it as a HTTP header:
views.py:
from django.views.decorators.csrf import ensure_csrf_cookie
# add this decorator to your main view
# (the one which serves your first html/javascript code, not the /api/register one)
#ensure_csrf_cookie
def index(request):
...
javascript:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
...
const config = {
headers:{
'Content-type': 'application/json',
'X-CSRFToken': getCookie("csrftoken") // added the csrf cookie header
}
}
const {data} = await axios.post('http://localhost:8000/api/register/',
{'email':email, 'password':password}, config)

How to show upload progress of json data in axios, XMLHttpRequest, fetch?

I'm trying to upload json data server in react-native. But the problem is, json data contain base64 image string. And I need display progress.
I tried like this, but it did not worked.
function handleEvent(e) {
setProgress((e.loaded / e.total) * 100)
}
function addListeners(xhr) {
xhr.upload.addEventListener('progress', handleEvent)
}
var xhr = new XMLHttpRequest();
addListeners(xhr);
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify(payload));
and using axios
var res = await axios.post(BASE_URL + '/crossstorage_addfile', payload, {
headers, onUploadProgress: function (progressEvent) {
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
console.log(percentCompleted)
}
});
But nothing worked. Anything I can do resolve?
thank you.

ionic 3 acces to json key

i can't access to a key of a json response from a restful web service.
{"_body":"{\"values\": {\"user_id\":\"1\",\"name\":\"fred test\",\"email\":\"fred#test.test\",\"username\":\"fredtest\",\"token\":\"d5f66a06ec809d70d0c52842df8dc0011d7d1ad0f2d56f50d3123da17a2489fe\"}}","status":200,"ok":true,"statusText":"OK","headers":{"pragma":["no-cache"],"content-type":["text/html;charset=UTF-8"],"cache-control":["no-store"," no-cache"," must-revalidate"],"expires":["Thu"," 19 Nov 1981 08:52:00 GMT"]},"type":2,"url":"http://localhost/PHP-Slim-Restful/api/login"}
I would like to acces to 'values' in this function: (this.responseData.values)
login(){
console.log('login'+ this.userData);
// Your app login API web service call triggers
this.authService.postData(this.userData,'login').then((result) => {
this.responseData = result;
console.log('userdata : '+ temp);
if(this.responseData.values){
console.log('response: ' + this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
this.navCtrl.push(TabsPage);
}
else{
this.showToastWithCloseButton()
}
}, (err) => {
console.log('erreur : '+err);
});
}
I have an error undifined!
Can you help me?
I have used Observable to return json data and using the subscribe function in my method and using response.json() to convert the JSON reponse from RESTful webservices.
My component method,
import {Http, Headers, Response, RequestOptions} from '#angular/http';
import {Observable} from 'rxjs/Rx';
var response = this.service.post('deleteUserDetails/'+this.selectedUserId, null);
response.subscribe((res) => {
var response = res.json();
});
Service Post method,
post(url: string, data : any): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers});
return this.http.post(url, data,{headers: headers});
}
I think this might be helpful for your query.
You can make a for in your JSON and access the return values of your post. Something like that.
"this.responseData = result.json();" -> Return JSON. Make a for.
Example:
public postData(data, url: string) {
this.http.post(url, data).toPromise().then(res => {
let responseData = res.json();
if (responseData) {
for (var item of responseData) {
//Implments
}
}
}, (err) => {
});
}

Set default header for every fetch() request

Is it possible, using the fetch API, to set default headers for every single request?
What I want to do is set an Authorization header whenever there is a json web token in the localStorage. My current solution is to set the headers with this function:
export default function setHeaders(headers) {
if(localStorage.jwt) {
return {
...headers,
'Authorization': `Bearer ${localStorage.jwt}`
}
} else {
return headers;
}
}
Setting the headers in a fetch request would then look like this:
return fetch('/someurl', {
method: 'post',
body: JSON.stringify(data),
headers: setHeaders({
'Content-Type': 'application/json'
})
})
But there has to be a better way to do this. I'm currently developing a React/Redux/Express app if that is of any help.
Creating a fetch wrapper could solve your problem:
function updateOptions(options) {
const update = { ...options };
if (localStorage.jwt) {
update.headers = {
...update.headers,
Authorization: `Bearer ${localStorage.jwt}`,
};
}
return update;
}
export default function fetcher(url, options) {
return fetch(url, updateOptions(options));
}
You also get the added benefit of being able to switch your request client easily for all the calls in your application if you decide you like Axios or other package better. And you can do other things like check if options.body is an object and add the 'Content-Type: application/json header.
You could use Axios instead of fetch, with Interceptors
const setAuthorization = (token) => {
api.interceptors.request.use((config) => {
config.headers.Authorization = 'Bearer ' + token;
return config;
});
}
Where Api is an axios Object with a base URL
const api= axios.create({
baseURL: 'http://exemple.com'
});
And when you get your token, u just have to call the function setAuthorization.
Source: Axios README.md
Andri Möll created a FetchDefaults.js mixin for fetch that sets fetch defaults:
var Url = require("url")
var assign = require("oolong").assign
var merge = require("oolong").merge
var PARSE_QUERY = false
var PROTOCOL_RELATIVE = true // Enable //example.com/models to mimic browsers.
exports = module.exports = function(fetch, rootUrl, defaults) {
if (typeof rootUrl === "string") rootUrl = parseUrl(rootUrl)
else defaults = rootUrl, rootUrl = null
return assign(exports.fetch.bind(null, fetch, rootUrl, defaults), fetch)
}
exports.fetch = function(fetch, rootUrl, defaults, url, opts) {
if (rootUrl != null) url = rootUrl.resolve(url)
if (typeof defaults === "function") defaults = defaults(url, opts)
return fetch(url, opts == null ? defaults : merge({}, defaults, opts))
}
function parseUrl(url) {
return Url.parse(url, PARSE_QUERY, PROTOCOL_RELATIVE)
}
Distributed under AGPL-3.0-only license
A quick and unrecommended hack is to redefine the default .fetch() function:
const oldFetch = window.fetch;
window.fetch = function() {
arguments[1].headers = { 'blahblah' : 'blabla' };
return oldFetch.apply(window, arguments);
}
Code is untested and unfinished. If you decide to use this answer, check arguments.length, add code to preserve existing headers, etc. etc. I'm just providing the direction for further exploration.
You can override default fetch api:
var originalFetch = window.fetch;
window.fetch = function (input, init) {
if (!init) {
init = {};
}
if (!init.headers) {
init.headers = new Headers();
}
// init.headers could be:
// `A Headers object, an object literal,
// or an array of two-item arrays to set request’s headers.`
if (init.headers instanceof Headers) {
init.headers.append('MyHeader', 'Value');
} else if (init.headers instanceof Array) {
init.headers.push(['MyHeader', 'Value']);
} else {
// object ?
init.headers['MyHeader'] = 'Value';
}
return originalFetch(input, init);
};
References:
https://fetch.spec.whatwg.org/#fetch-method
https://fetch.spec.whatwg.org/#requestinit

Resources