angular2 xhrfields withcredentials true - javascript

I am trying to login to a system. In angular 1, there was ways to set
withCredentials:true
But I could not find a working solution in angular2
export class LoginComponent {
constructor(public _router: Router, public http: Http, ) {
}
onSubmit(event,username,password) {
this.creds = {'Email': 'harikrishna#gmail.com','Password': '01010','RememberMe': true}
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.http.post('http://xyz/api/Users/Login', {}, this.creds)
.subscribe(res => {
console.log(res.json().results);
});
}
}

In Angular > 2.0.0 (and actually from RC2 on), just
http.get('http://my.domain.com/request', { withCredentials: true })

AFAIK, right now (beta.1) the option is not available.
You have to work around it with something like this:
let _build = http._backend._browserXHR.build;
http._backend._browserXHR.build = () => {
let _xhr = _build();
_xhr.withCredentials = true;
return _xhr;
};

This issue has been noted by the angular2 team.
You can find some other workarounds (one especially written as an #Injectable) following the issue link.

If anyone is using plain JS, based on cexbrayat's answer:
app.Service = ng.core
.Class({
constructor: [ng.http.Http, function(Http) {
this.http = Http;
var _build = this.http._backend._browserXHR.build;
this.http._backend._browserXHR.build = function() {
var _xhr = _build();
_xhr.withCredentials = true;
return _xhr;
};
}],

I think you don't use the post metrhod the right way. You could try something like that:
onSubmit(event,username,password) {
this.creds = {
'Email': 'harikrishna#gmail.com',
'Password': '01010','RememberMe': true
}
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.http.post('http://xyz/api/Users/Login',
JSON.stringify(this.creds),
{ headers: headers });
}
You invert parameters. The second parameter corresponds to the content to send into the POST and should be defined as string. Objects aren't supported yet at this level. See this issue: https://github.com/angular/angular/issues/6538.
If you want to set specific headers, you need to add the Headers object within the third parameter of the post method.
Otherwise, I think the withCredentials property is related to CORS if you want to send cookies within cross domain requests. You can have a look at this link for more details:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Hope it helps you,
Thierry

getHeaders(): RequestOptions {
let optionsArgs: RequestOptionsArgs = { withCredentials: true }
let options = new RequestOptions(optionsArgs)
return options;
}
getAPIData(apiName): Observable<any> {`enter code here`
console.log(Constants.API_URL + apiName);
let headers = this.getHeaders();
return this.http
.get(Constants.API_URL + apiName, headers)
.map((res: Response) => res.json())
}
Enabled cors in the webapi
Same code works fine in the chrome(normal),Internet explorer
But it is asking windows login prompt in the incognito chrome,firefox,edge.
Share the suggestions how to fix the issue

for CORS issue with withCredentials : yes, I send the auth token as parameter
req = req.clone({
//withCredentials: true,
setHeaders: { token: _token },
setParams: {
token: _token,
}
});

Related

Vimeo API Upload Progress

I'm using the Vimeo API to upload videos and am trying to track the progress of the upload.
The documentation here is pretty straightforward:
https://developer.vimeo.com/api/upload/videos
However, I can't seem to figure out how to retrieve Upload-Length and Upload-Offset from the HEAD response.
I call the "uploadVideo" function below to upload the video to Vimeo (this function does as it should). I then call the "getProgress" function and this is where things go awry. I've tried many variations of this code, but none have worked.
async function uploadVideo(upload_link : string) {
const uploadResponse = await fetch(upload_link, {
method: 'PATCH',
headers: {
'Tus-Resumable': '1.0.0',
'Upload-Offset': '0',
'Content-Type': 'application/offset+octet-stream'
},
body: accepted
});
}
async function getProgress(upload_link : string) {
const progress = await fetch(upload_link, {
method: 'HEAD',
headers: {
'Tus-Resumable': '1.0.0',
'Accept': 'application/vnd.vimeo.*+json;version=3.4'
},
});
const currentProgress = await progress;
console.log(currentProgress);
// if (currentProgress.upload_length != currentProgress.upload_offset) {
// getProgress(upload_link)
// }
}
If I await progress.json(), I get a SyntaxError: Unexpected end of JSON input
I'm somewhat surprised that there are no up-to-date JavaScript examples of this process out there on the interwebs. Any assistance would be greatly appreciated.
Thank you for your time.
As #Clive pointed out above, to access the necessary headers, one would use:
uploadLength = progress.headers.get('upload-length');
uploadOffset = progress.headers.get('upload-offset');
This answers my specific question.
However, if you're only using the Vimeo API, you'll find that there's another challenge once this is complete. In the original code posted above, you'll never be able to track the progress of the upload with a HEAD request because the "upload-offset" value is always 0 until the initial PATCH request is completed, i.e. it's 0 until the PATCH request is complete and once it's complete it jumps directly to 100%.
To get around this issue, I decided to use "tus-js-client." So, if you've made it to where my code above leaves off, instead of using the above functions you could just pass the link (in this example, "upload_link") and the file (in this example, "accepted") to:
async function uploadVideo(upload_link : string) {
// Create the tus upload similar to the example from above
var upload = new tus.Upload(accepted, {
uploadUrl: upload_link,
onError: function(error) {
console.log("Failed because: " + error)
},
onProgress: function(bytesUploaded, bytesTotal) {
var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
console.log(bytesUploaded, bytesTotal, percentage + "%")
},
onSuccess: function() {
console.log("Download %s from %s", upload.file.path, upload.url)
}
})
// Start the upload
upload.start()
}
And here's the server-side code to get the "upload_link":
export const actions: Actions = {
upload: async ({ request }) => {
const uploadFormData = await request.formData();
const accepted = uploadFormData.get('accepted-file') as File;
const response = await fetch(`https://api.vimeo.com/me/videos`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `bearer ${import.meta.env.VITE_VIMEO_ACCESS_TOKEN}`,
'Accept': 'application/vnd.vimeo.*+json;version=3.4'
},
body: JSON.stringify({
upload: {
"approach": "tus",
"size": accepted.size
}
})
});
const dataResponse = await response.json();
return {
upload: dataResponse.upload
}
}
}
This server response is returned to a client-side "handleSubmit" function, which in turn calls the "uploadVideo" function, like so uploadVideo(result.data.upload.upload_link).
I was initially using "vimeo-upload" to accomplish this. The problems with vimeo-upload are (1) it exposes your access token to the browser and (2) the code base is outdated. I'd advise to stay away from vimeo-upload at all costs!
For what it's worth, this is a SvelteKit implementation.
If you're using SvelteKit, best to not use an import.meta.env.VITE prefixed environment variable; it should be a "private" environment variable as shown here:
https://joyofcode.xyz/sveltekit-environment-variables
I had such a hard time figuring out how to do this. I hope that this example will help someone in the future.

CORS No 'Access-Control-Allow-Origin' error in React app w/ Facebook

I'm a junior developer that's fairly new to using Facebook for Developers. I'm hitting a wall with the ReactJs application I'm building and could use your help!
My boss has requested a Grid representation of the Page Plugin, not the actual Plugin itself. For this project, he's requested I make and use a test 'Page' I've found that DevExtreme's Data Grid seems to be the best option in terms of the desired visual, and I'm trying to call my Facebook Page using the Graph API documentation. I know it's hitting at least the area I want it to with my console.log because it's returning the error message.
Here are the errors my browser is returning:
Access to fetch at 'https://www.facebook.com/Feeds-Tester-170107151801959/' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET https://www.facebook.com/Feeds-Tester-170107151801959/ net::ERR_FAILED
The link you'll see referenced in my URL variable has been triple checked to be the correct link. Since I'm using NodeJS, I tried installing the CORS npm package but I'm not 100% sure where to put it to use it, I'm wondering if that's the cause of the issue?
Here's my full code snippet (I'm using VS Code, if that helps):
/*global FB*/
import React from 'react';
import { DataGrid, Editing, Scrolling, Lookup, Summary, TotalItem } from 'devextreme-react/data-grid';
import { Button } from 'devextreme-react/button';
import { SelectBox } from 'devextreme-react/select-box';
import CustomStore from 'devextreme/data/custom_store';
import { formatDate } from 'devextreme/localization';
import 'whatwg-fetch';
const URL = 'https://www.facebook.com/Feeds-Tester-170107151801959/';
const REFRESH_MODES = ['full', 'reshape', 'repaint'];
class Grid extends React.Component {
constructor(props) {
super(props);
this.state = {
fbData: null,
ordersData: new CustomStore({
key: 'OrderID',
load: () => this.sendRequest(`${URL}`, 'GET'),
}),
requests: [],
refreshMode: 'reshape'
};
this.clearRequests = this.clearRequests.bind(this);
this.handleRefreshModeChange = this.handleRefreshModeChange.bind(this);
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Post ID: ' + response.id);
}
})
}
sendRequest(url, method, data) {
method = method || 'GET';
data = data || {};
this.logRequest(method, url, data);
if(method === 'GET') {
return fetch(url, {
method: method,
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
}
}).then(result => result.json().then(json => {
if(result.ok) return json.data;
throw json.Message;
}));
}
const params = Object.keys(data).map((key) => {
return `${encodeURIComponent(key) }=${ encodeURIComponent(data[key])}`;
}).join('&');
return fetch(url, {
method: method,
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
credentials: 'include'
}).then(result => {
if(result.ok) {
return result.text().then(text => text && JSON.parse(text));
} else {
return result.json().then(json => {
throw json.Message;
});
}
});
}
logRequest(method, url, data) {
const args = Object.keys(data || {}).map(function(key) {
return `${key }=${ data[key]}`;
}).join(' ');
const time = formatDate(new Date(), 'HH:mm:ss');
const request = [time, method, url.slice(URL.length), args].join(' ');
this.setState((state) => {
return { requests: [request].concat(state.requests) };
});
}
clearRequests() {
this.setState({ requests: [] });
}
handleRefreshModeChange(e) {
this.setState({ refreshMode: e.value });
}
render() {
const { refreshMode, ordersData } = this.state;
return (
<React.Fragment>
<DataGrid
id="grid"
showBorders={true}
dataSource={ordersData}
repaintChangesOnly={true}
>
<Editing
refreshMode={refreshMode}
mode="cell"
allowAdding={true}
allowDeleting={true}
allowUpdating={true}
/>
<Scrolling
mode="virtual"
/>
<Lookup dataSource={ordersData} valueExpr="Value" displayExpr="Text" />
<Summary>
{/* <TotalItem column="CustomerID" summaryType="count" />
<TotalItem column="Freight" summaryType="sum" valueFormat="#0.00" /> */}
</Summary>
</DataGrid>
<div className="options">
<div className="caption">Options</div>
<div className="option">
<span>Refresh Mode: </span>
<SelectBox
value={refreshMode}
items={REFRESH_MODES}
onValueChanged={this.handleRefreshModeChange}
/>
</div>
<div id="requests">
<div>
<div className="caption">Network Requests</div>
<Button id="clear" text="Clear" onClick={this.clearRequests} />
</div>
<ul>
{this.state.requests.map((request, index) => <li key={index}>{request}</li>)}
</ul>
</div>
</div>
</React.Fragment>
);
}
}
export default Grid;
This is the link to the docs for the module I'm trying to reference
I'm trying to not bite off more than I can chew and just start with retrieving the data before I even think about manipulating it or sending any in return. Any insight or guidance you can provide would be greatly appreciated. Thank you!! :)
Do not use fetch with the Facebook URL, it won't let it happen on the browser, instead, use the Facebook API for everything you need to do with it
For example, instead of fetching the page, use the api with the page
FB.api('/Feeds-Tester-170107151801959', function(response) {
// ...
});
If you need to fetch the page, then you have to do it outside the browser environment or use a proxy like cors anywhere, but you can avoid that by using the Facebook API
I was also getting these error. I found that the pageId, I was using was wrong🤦‍♀️. These errors come only when your pageId is wrong or the domain is not whitelisted properly(I even tried with a ngrok url and it worked😵).
So the steps which I followed were:
In buisness.facebook.com go to inbox from sidebar and select chat plugin. [https://i.stack.imgur.com/rDk5d.png]
Click on setup to add your domain. [https://i.stack.imgur.com/exOi2.png]
Pick a setup method(standard for react/nextjs) and setup chat plugin(add language, domain, copy code and paste it). [https://i.stack.imgur.com/hDArZ.png]
You can add multiple domains. [https://i.stack.imgur.com/zGdgx.png]
You will get pageId already embedded. [https://i.stack.imgur.com/iRT13.png]
Use this code and paste it in _document.js file in nextjs. and after deploying it will work perfectly. For any confusion please let me know. Thanks, Happy Coding ☺

react and axios POST throws an Uncaught (in promise) TypeError: parsed is undefined

I'm baffled what I'm doing wrong in my code. The GET call gets resolved, but when I try to do a POST call to the same server I get an error. My POST endpoint works fine with Postman.
apiConnection.js
function get(data){
return axios.get("http://localhost:8080/api/questions",
{
params:data.payload
}, {
headers: {
'accept': 'application/json',
}
})
}
function post(data){
console.log(data.payload) //my payload is received here
return axios.post("http://localhost:8080/api/answer", {
params:data.payload
}, {
headers: {
'accept': 'application/json',
}
}
)
}
export { get, post }
Here is the error I get in the console
And here is how I make the call in react
index.js
GET (Receives response normally)
import { get, post } from "apiConnection.js"
...
componentDidMount(){
const data = {
payload: {
linkId: getSlug()
}
}
get(data).then((result) => {
this.setState({reportId: result.data.report.id});
})
}
POST (Throws error)
vote(userVote){
const data = {
payload: {
reportId: this.state.reportId,
}
}
post(data).then((result)=>{
this.state.questions[this.state.currentQuestion].vote = userVote
});
}
I have found the culprit of the issue but if someone can add more information about it, it might be helpful for others.
In my question, for brevity, I changed the request URL from imported constants to hardcoded links.
In my code, I have a variable for both GET and POST
return axios.post(apiEndpoints[data.ep], data.payload)
I import the endpoint variables like so
import * as apiEndpoints from './apiEndpoints';
apiEndpoints.js
const server = 'http://localhost:8080/'
const api_version = 'api/'
const base_url = server+api_version;
export const EP_QUESTIONS = base_url+'questions';
export const EP_ANSWER = base_url+'answer';
For some unknown reason EP_ANSWER throws the error even though I'm not making a typo when I define data.ep (data.ep has EP_ANSWER, which
I checked a million times)
The solution was to just change EP_ANSWER to EP_ANS and everything worked as expected.
No idea why this is the case. It might be some global variable or a reserved word.
Just came across this and noted #Ando's response.
So, knowing that I first tried a hard coded URL, it worked.
I then successfully did url.toString() and it worked.
Not sure why but Javascript seems to treat a an object string differently than a true string.

Using adapter headers outside of ActiveModelAdapter

I've got my authorization system working nicely with Ember Data. All my ember-data calls are signed with the correct tokens by using adapater.ajax() instead of $.ajax. However, I've got a case where I am using a 3rd party upload library which uses its own XHR request (jquery.fileapi). This library exposes a "headers" property for the requests it makes, but I'm not sure what the best way is to get the headers out of my adapter and pass it the file upload component I'm building.
ApplicationAdapter:
export default DS.ActiveModelAdapter.extend({
namespace: 'api/v1',
headers: function() {
var authToken = this.get('session.authToken') || 'None';
return {
'Authorization': Ember.String.fmt('Bearer %#', authToken)
};
}.property('session.authToken')
});
ImageUploadComponent:
didInsertElement: function() {
this.$('.js-uploader').fileapi({
url: '/api/v1/users/avatar',
accept: 'image/*',
headers: {'?????????????'}
});
}
I'd rather not define a global in "headers" when the 'session.authToken' changes.
Here's what I'm doing for now. Would love other solutions.
DS.Store.reopen({
apiPathFor: function() {
var url = arguments.length ? Array.prototype.slice.call(arguments).join('/') : ''
, adapter = this.adapterFor('application');
return [adapter.urlPrefix(), url].join('/');
}
});
export default Ember.Component.extend({
endpoint: null,
store: Ember.computed.readOnly('targetObject.store'),
didInsertElement: function() {
var store = this.get('store')
, adapter = store.adapterFor('application')
, headers = adapter.get('headers')
, url = store.apiPathFor(this.get('endpoint'));
var args = {
url: url,
headers: headers,
accept: 'image/*'
};
this.$('.js-fileapi').fileapi(args);
},
});

AngularJS: How to send auth token with $resource requests?

I want to send an auth token when requesting a resource from my API.
I did implement a service using $resource:
factory('Todo', ['$resource', function($resource) {
return $resource('http://localhost:port/todos.json', {port:":3001"} , {
query: {method: 'GET', isArray: true}
});
}])
And I have a service that stores the auth token:
factory('TokenHandler', function() {
var tokenHandler = {};
var token = "none";
tokenHandler.set = function( newToken ) {
token = newToken;
};
tokenHandler.get = function() {
return token;
};
return tokenHandler;
});
I would like to send the token from tokenHandler.get with every request send via the Todo service. I was able to send it by putting it into the call of a specific action. For example this works:
Todo.query( {access_token : tokenHandler.get()} );
But I would prefer to define the access_token as a parameter in the Todo service, as it has to be sent with every call. And to improve DRY.
But everything in the factory is executed only once, so the access_token would have to be available before defining the factory and it cant change afterwards.
Is there a way to put a dynamically updated request parameter in the service?
Thanks to Andy Joslin. I picked his idea of wrapping the resource actions. The service for the resource looks like this now:
.factory('Todo', ['$resource', 'TokenHandler', function($resource, tokenHandler) {
var resource = $resource('http://localhost:port/todos/:id', {
port:":3001",
id:'#id'
}, {
update: {method: 'PUT'}
});
resource = tokenHandler.wrapActions( resource, ["query", "update"] );
return resource;
}])
As you can see the resource is defined the usual way in the first place. In my example this includes a custom action called update. Afterwards the resource is overwritten by the return of the tokenHandler.wrapAction() method which takes the resource and an array of actions as parameters.
As you would expect the latter method actually wraps the actions to include the auth token in every request and returns a modified resource. So let's have a look at the code for that:
.factory('TokenHandler', function() {
var tokenHandler = {};
var token = "none";
tokenHandler.set = function( newToken ) {
token = newToken;
};
tokenHandler.get = function() {
return token;
};
// wrap given actions of a resource to send auth token with every
// request
tokenHandler.wrapActions = function( resource, actions ) {
// copy original resource
var wrappedResource = resource;
for (var i=0; i < actions.length; i++) {
tokenWrapper( wrappedResource, actions[i] );
};
// return modified copy of resource
return wrappedResource;
};
// wraps resource action to send request with auth token
var tokenWrapper = function( resource, action ) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original and sending token
resource[action] = function( data, success, error){
return resource['_' + action](
angular.extend({}, data || {}, {access_token: tokenHandler.get()}),
success,
error
);
};
};
return tokenHandler;
});
As you can see the wrapActions() method creates a copy of the resource from it's parameters and loops through the actions array to call another function tokenWrapper() for every action. In the end it returns the modified copy of the resource.
The tokenWrappermethod first of all creates a copy of preexisting resource action. This copy has a trailing underscore. So query()becomes _query(). Afterwards a new method overwrites the original query() method. This new method wraps _query(), as suggested by Andy Joslin, to provide the auth token with every request send through that action.
The good thing with this approach is, that we still can use the predefined actions which come with every angularjs resource (get, query, save, etc.), without having to redefine them. And in the rest of the code (within controllers for example) we can use the default action name.
Another way is to use an HTTP interceptor which replaces a "magic" Authorization header with the current OAuth token. The code below is OAuth specific, but remedying that is a simple exercise for the reader.
// Injects an HTTP interceptor that replaces a "Bearer" authorization header
// with the current Bearer token.
module.factory('oauthHttpInterceptor', function (OAuth) {
return {
request: function (config) {
// This is just example logic, you could check the URL (for example)
if (config.headers.Authorization === 'Bearer') {
config.headers.Authorization = 'Bearer ' + btoa(OAuth.accessToken);
}
return config;
}
};
});
module.config(function ($httpProvider) {
$httpProvider.interceptors.push('oauthHttpInterceptor');
});
I really like this approach:
http://blog.brunoscopelliti.com/authentication-to-a-restful-web-service-in-an-angularjs-web-app
where the token is always automagically sent within the request header without the need of a wrapper.
// Define a new http header
$http.defaults.headers.common['auth-token'] = 'C3PO R2D2';
You could create a wrapper function for it.
app.factory('Todo', function($resource, TokenHandler) {
var res= $resource('http://localhost:port/todos.json', {
port: ':3001',
}, {
_query: {method: 'GET', isArray: true}
});
res.query = function(data, success, error) {
//We put a {} on the first parameter of extend so it won't edit data
return res._query(
angular.extend({}, data || {}, {access_token: TokenHandler.get()}),
success,
error
);
};
return res;
})
I had to deal with this problem as well. I don't think if it is an elegant solution but it works and there are 2 lines of code :
I suppose you get your token from your server after an authentication in SessionService for instance. Then, call this kind of method :
angular.module('xxx.sessionService', ['ngResource']).
factory('SessionService', function( $http, $rootScope) {
//...
function setHttpProviderCommonHeaderToken(token){
$http.defaults.headers.common['X-AUTH-TOKEN'] = token;
}
});
After that all your requests from $resource and $http will have token in their header.
Another solution would be to use resource.bind(additionalParamDefaults), that return a new instance of the resource bound with additional parameters
var myResource = $resource(url, {id: '#_id'});
var myResourceProtectedByToken = myResource.bind({ access_token : function(){
return tokenHandler.get();
}});
return myResourceProtectedByToken;
The access_token function will be called every time any of the action on the resource is called.
I might be misunderstanding all of your question (feel free to correct me :) ) but to specifically address adding the access_token for every request, have you tried injecting the TokenHandler module into the Todo module?
// app
var app = angular.module('app', ['ngResource']);
// token handler
app.factory('TokenHandler', function() { /* ... */ });
// inject the TokenHandler
app.factory('Todo', function($resource, TokenHandler) {
// get the token
var token = TokenHandler.get();
// and add it as a default param
return $resource('http://localhost:port/todos.json', {
port: ':3001',
access_token : token
});
})
You can call Todo.query() and it will append ?token=none to your URL. Or if you prefer to add a token placeholder you can of course do that too:
http://localhost:port/todos.json/:token
Hope this helps :)
Following your accepted answer, I would propose to extend the resource in order to set the token with the Todo object:
.factory('Todo', ['$resource', 'TokenHandler', function($resource, tokenHandler) {
var resource = $resource('http://localhost:port/todos/:id', {
port:":3001",
id:'#id'
}, {
update: {method: 'PUT'}
});
resource = tokenHandler.wrapActions( resource, ["query", "update"] );
resource.prototype.setToken = function setTodoToken(newToken) {
tokenHandler.set(newToken);
};
return resource;
}]);
In that way there is no need to import the TokenHandler each time you want to use the Todo object and you can use:
todo.setToken(theNewToken);
Another change I would do is to allow default actions if they are empty in wrapActions:
if (!actions || actions.length === 0) {
actions = [];
for (i in resource) {
if (i !== 'bind') {
actions.push(i);
}
}
}

Categories

Resources