node.js - Angular 2 - Consuming restful api calls with windows authentication -
i have .net web api hosted on iis 7 on remote server uses windows authentication. want access web api using angular 2 using typescript node. earlier getting error 'response preflight request doesn't pass access control check: no 'access-control-allow-origin' header present on requested resource'
i added on hosted application's web.config
<httpprotocol> <customheaders> <add name="access-control-allow-origin" value="*" /> </customheaders>
but unauthorised 401 error. have read adding following code allow cross domain access - don't have idea add in angular 2 app , how compile.
app.use(function(req, res, next) { res.header("access-control-allow-origin", "*"); res.header("access-control-allow-headers", "origin, x-requested-with, content-type, accept"); next(); }); app.get('/', function(req, res, next) { // handle route }); app.post('/', function(req, res, next) { // handle post route });
here sample code service trying make call with
@injectable() export class todoservice { todos$: observable<todo[]>; private _baseurl: string; private _todosobserver: observer<todo[]>; private _datastore: { todos: todo[] }; constructor(private _http: http) { //let headers: headers = new headers(); this._baseurl = 'http:/sampleserver/server/api/loadtodo'; this.todos$ = new observable(observer => this._todosobserver = observer).share(); this._datastore = { todos: [] }; } loadtodos() { let headers: headers = new headers(); //headers.append('access-control-allow-origin'); headers.append('authorization', 'basic ' + btoa('username:password')); //let opts: requestoptions = new requestoptions(); //opts.headers = headers; this._http.get(`${this._baseurl}`,headers).map(response => response.json()).subscribe(data => { this._datastore.todos = data; this._todosobserver.next(this._datastore.todos); }, error => console.log('could not load todos.')); }
any resolve issue great.
you need check if authorization
header correctly sent within request. if forgot import headers
class, header won't sent:
import {http, headers, ...} 'angular2/http';
another option that, since in case of preflighted request (get method authorization
header), options request sent. in fact, request transparently sent browser , credentials present in it. don't have check security here on server side. otherwise have 401 error since server won't able authenticate request...
see these articles more details:
Comments
Post a Comment