loginservice
export class LoginService {
public token: any;
constructor( private http:HttpClient) { }
login(body) {
const headers=new HttpHeaders;
headers.append('content-Type', 'application/json'),
headers.append('api_key', '7zttgA4kFVsD2V2n0beMpzdLQRiSAKxtVEpyeW9MaEFEND0g')
return this.http.post('https://bell.s2c.io/api/v1/Login', body,
{ headers: headers }).pipe(res=>{return res})
}}
login.ts
export class LoginPage implements OnInit {
private formlogin : FormGroup;
userId : any
token : any
constructor(private formBuilder: FormBuilder,private servicelogin:LoginService,
public toastController: ToastController,private router : Router)
{
this.formlogin = this.formBuilder.group({
username: ['', Validators.required],
password: [''],
});}
logForm(){
//console.log(this.formlogin.value);
this.servicelogin.login(this.formlogin.value).subscribe(data=>{
let res: any
res = data;
console.log(res);
//this.router.navigateByUrl('/home')
})
}
ngOnInit() {
}
}
Problem **
Access to XMLHttpRequest at 'https://bell.s2c.io/api/v1/Login' from origin 'http://localhost:8101' 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.
**someone can help me?
This is likely an error with your backend not handling CORS properly. Since you are using Flask I would checkout this question.
You can also install browser plugins to help like this one.
Related
I have url, this url needs authentication with username and password. On PHP I made it with curl_setopt(CURLOPT_USERPWD, $username . ':' . $password), I can't find any solution how to set password and username on same link on NestJS.
import { Injectable, Scope, HttpService } from '#nestjs/common';
import { ImporterService } from '../importer.service';
import { map } from 'rxjs/operators';
#Injectable({ scope: Scope.REQUEST })
export class Supplier extends ImporterService {
supplierName = 'supplierName';
fileDownload: boolean = false;
username = 'username;
password = 'password';
async parse() {
await this.checkSupplierExist(this.supplierName);
return this.httpService
.get(
'https://www.link.com/restful/export/api/products.xml?acceptedlocales=en_US&addtags=true',
)
.pipe( map(response => console.log(response)));
}
}
this response sends 401, cause it needs authentication. I cannot figure out how to set username or password. Can anyone help?
From me I have a Config service which handles http calls, looks like this:
#Injectable()
export class ConfigService {
private readonly envConfig: { [key: string]: string };
private servers: Object = {};
constructor(private httpService: HttpService) {
this.envConfig = {
PORT: process.env.PORT,
MONGODB_URI: process.env.MONGODB_URI,
MONGODB_SESSION_URI: process.env.MONGODB_SESSION_URI,
SESSION_SECRET: process.env.SESSION_SECRET
};
const externals = JSON.parse(process.env.EXTERNALS);
for (const lang in externals) {
this.servers[lang] = externals[lang];
}
}
get(key: string): string {
return this.envConfig[key];
}
getServer(lang: string, method: string, url: string, headers: Object, params?: Object, data?: Object) {
const config = { baseURL: this.servers[lang], url, headers, method, data, params };
return this.httpService.request(config).toPromise();
}
}
As you can see in the getServer method, you can add headers as well.
I hope this is what you're looking for
I am working in an Angular 6 application and I was wondering what should be the best practice when customizing the url while sending requests to the server.
Here is the scenario:
- In my Angular project I have the environment.ts and environment.prod.ts where I added a "host" which contains the url:port of the http server (project with the controllers).
- I am creating Services to be injected in my components which will be responsible for sending requests (GETs and POSTs) to the server to retrieve data or to send updates.
- I want to use the "host" from the environment.ts as part of the request url. So ALL my requests will have the "host" as the base url and then i can concatenate to the desired path.
I already checked a few solutions and I already implemented one of them, but I am not sure this is the right practice. I will write below what i implemented so far and then i will write some ideas, please help me understand what is the best solution (I am new at angular)
Currently implemented:
-> In my feature services, like LoginService, I inject the angular HttpClient. Then I simply call:
return this.httpService.post("/login/", creds).pipe(
map((data: any) => {
this.manager = data;
return this.manager;
}));
I created an interceptor to make changes to the url: InterceptService implements HttpInterceptor where I create a new instance of the HttpRequest and customize the request.url using environment.host. I also needed the interceptor to add a Header for the authentication (still not fully implemented)
const httpRequest = new HttpRequest(<any>request.method, environment.host + request.url, request.body);
request = Object.assign(request, httpRequest);
const headers = new HttpHeaders({
'Authorization': 'Bearer token 123',
'Content-Type': 'application/json'
});
Questions:
1) This works, all my requests are changed in the interceptor as I
wanted, but it doesn't look like the best practice in my first look. I
don't like to create a new HeepRequest to be able to do this (i did it
to keep it immutable, I guess that's the correct way). Do you think
this looks good?
2) What about the Authentication being added to the Header in the interceptor? Is it ok? Most of the references I checked did this
Other solutions:
1) I saw some examples where a HttpClientService extends Http and each of the methods such as get and post edit the url and headers before calling super methods. But I believe this is not Angular 6 and is probably not preferrable
2) I could also create a service that receives an angular HttpClient (angular 6 HttpClientModule) instance by injection and I could implement the methods like get or post.
Well, as I didn't get any answers I will add my solution. i believe it's the best solution based on my researches.
I used an interceptor for adding information to the header such as the
token bearer authentication.
import { Injectable } from '#angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpHeaders,
HttpErrorResponse
} from '#angular/common/http'
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { environment } from "../../../environments/environment";
import { Router } from "#angular/router";
export class HttpClientInterceptor implements HttpInterceptor {
constructor(private router: Router) { }
// intercept request to add information to the headers such as the token
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//I decided to remove this logic from the interceptor to add the host url on the HttpClientService I created
//const httpRequest = new HttpRequest(<any>request.method, environment.host + request.url, request.body);
//request = Object.assign(request, httpRequest);
var token = localStorage.getItem("bearerToken");
if (token) {
const newReq = request.clone(
{
headers: request.headers.set('Authorization',
'Bearer ' + token)
});
return next.handle(newReq).pipe(
tap(event => {
if (event instanceof HttpResponse) {
console.log("Interceptor - HttpResponse = " + event.status); // http response status code
}
}, error => {
// http response status code
if (error instanceof HttpErrorResponse) {
console.log("----response----");
console.error("status code:");
console.error(error.status);
console.error(error.message);
console.log("--- end of response---");
if (error.status === 401 || error.status === 403) //check if the token expired and redirect to login
this.router.navigate(['login']);
}
})
)
}
else {
return next.handle(request);
}
};
For changing the url, I created a service on file
http-client.service.ts and got the host url from environment.ts
import { Injectable } from "#angular/core";
import { HttpClient } from '#angular/common/http';
import { Observable } from "rxjs";
import { environment } from "../../../environments/environment";
#Injectable({ providedIn:'root' })
export class HttpClientService {
constructor(private http: HttpClient) { }
get(url: string, options?: any): Observable<ArrayBuffer> {
url = this.updateUrl(url);
return this.http.get(url, options);
}
post(url: string, body: string, options?: any): Observable<ArrayBuffer> {
url = this.updateUrl(url);
return this.http.post(url, body, options);
}
put(url: string, body: string, options?: any): Observable<ArrayBuffer> {
url = this.updateUrl(url);
return this.http.put(url, body, options);
}
delete(url: string, options?: any): Observable<ArrayBuffer> {
url = this.updateUrl(url);
return this.http.delete(url,options);
}
private updateUrl(req: string) {
return environment.host + req;
}
}
As i said, I believe this is the best approach, but feel free to add information to my question/answer.
I am getting the error message in cli like :
Type 'Headers' has no properties in common with type 'RequestOptionsArgs'
. However, the code executes. The version I am using is 5, as it shows in package.json. I am unable to find a good http example, which suit my need. I want to send some parameters in headers section, and authorize it in php. Here is the service code:
user.service.ts
import { Observable } from 'rxjs/Observable';
import { Customer } from './../models/customer';
import { Injectable } from "#angular/core";
import { Http, Response, Headers, RequestOptions } from "#angular/http";
import "rxjs/add/operator/map";
import { apiServicesURL,appServicesURL } from "../constants/globals";
import { HttpClient, HttpHeaders } from "#angular/common/http";
#Injectable()
export class UserService {
//headers : Headers ;
constructor(private http: Http) {
}
getCustomerInfoo(custId): Observable<Customer> {
//cust.push({token : localStorage.getItem('token')});
console.log(apiServicesURL + 'getCustomers');
let token = localStorage.getItem('token');
let api_token = localStorage.getItem('api_token');
let email = localStorage.getItem('email');
let headers = new Headers({ 'Content-Type': 'application/json' });
// let options: RequestOptions = new RequestOptions({ headers: headers });
return this.http.post(apiServicesURL + 'getCustomers', JSON.stringify({ customer_id: custId, token: api_token, email: email }), headers ).map((response: Response) => {
// login successful if there's a jwt token in the response
return <Customer>response.json();
});
}
}
Any help, appreciated!!!
If you are using angular 5 then try it this below code and write RequestOptionsProvider to module.ts file
import { Injectable } from '#angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS } from '#angular/common/http';
import { AuthService } from '#app/core/services/auth.service';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class DefaultRequestOptionsService implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
// const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
// const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
const authReq = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
export const RequestOptionsProvider = { provide: HTTP_INTERCEPTORS, useClass: DefaultRequestOptionsService, multi: true };
I want to add headers to post request from Angular 5 web app.
I've created the following Injectable class, registered in my app module:
#Injectable()
export class headerInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header
const authReq = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
})
});
return next.handle(authReq);
}
}
I have network communication service and Im adding body parameters as below.
#Injectable()
export class NetworkService {
Root:string = 'some valid url';
results:Object[];
loading:boolean;
// inject Http client to our client service.
constructor(private httpClient: HttpClient ) {
}
login(loginParams : URLSearchParams){
let baseURL = `${this.Root}/login`;
this.httpClient.post(baseURL, JSON.stringify({'UserName':'123','Password':'123'} ))
.subscribe(data => {
console.log();
},
err => {
console.log('Error: ' + err.error);
});
when I put breakpoint after the clone method inside headerInterceptor class I can see the request body.
the problem is when I switch to network tab in chrome, I get 405 error and I can't see the body and the new headers. when I return the original request 'req'
the body sent ok but no new headers of course.
App Module,
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { headerInterceptor } from './httpinterceptor'
Add it to providers,
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: headerInterceptor,
multi: true
}
],
Now change the intereptor to, I have changed the way headers are added
#Injectable()
export class headerInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers:req.headers.set("Content-Type", "application/json; charset=utf-8")
});
return next.handle(authReq);
}
}
}
You can also use setHeaders:
#Injectable()
export class headerInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {y
req = req.clone({
setHeaders: {
"Content-Type": "application/json; charset=utf-8"
}
});
return next.handle(req);
}
}
My problem was on server side I'm using ASP.net and wcf.
it seems that the server must implement CORS support when working with Angular 5 project (works ok with jQuery and cross domain tag).
this post helped me to add support in CORS:
http://blogs.microsoft.co.il/idof/2011/07/02/cross-origin-resource-sharing-cors-and-wcf/
How can I intercept the server endpoint response and redirect an aurelia application to login page if is a 401 response?
I tried "withInterceptor(responseError() {...})" method of aurelia-fetch-client config, but I cannot return a "new Redirect(loginPage)"...
Anyone has an idea how to do it?
Here's an example:
import { HttpClient } from 'aurelia-fetch-client';
import { inject } from 'aurelia-framework'
import { Router } from 'aurelia-router'
#inject(HttpClient, Router)
export class UserService {
http
router
constructor(http, router) {
this.http = http
this.router = router
this.http.configure(config => {
var self = this;
config
.withInterceptor({
responseError(response) {
if (response.status === 401) {
self.router.navigateToRoute('login')
}
return response; // you can return a modified Response
},
});
});
}
#Moustachiste fix same issue with this approach:
inject must be like this
constructor(
// private _router: Router
#lazy(Router) private _router: () => Router
)