Nau*_*lla 7 java servlets angular
我正在尝试做一个http.post,但chrome显示以下错误:
无访问控制允许原点.
我的Angular功能是:
onSubmit(event: Event) {
event.preventDefault();
this.leerDatos()
.subscribe(res => {
//datos = res.json();
console.log("Data send");
}, error => {
console.log(error.json());
});
}
leerDatos(): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(`http://localhost:8080/LegoRepositoryVincle/CoreServlet`, { name: "bob" }, options)
//.map(this.extractData)
//.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
而我的servlet doPost方法包括:
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.addHeader("Access-Control-Allow-Origin","http://localhost:4200");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods","GET,POST");
response.addHeader("Access-Control-Allow-Headers","X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Pragma");
Run Code Online (Sandbox Code Playgroud)
And*_*M16 14
如果你仍然想在开发时使用CORS,你可以使用angular/cli --proxy-config解决这类问题.
基本上,如果您想要对运行nginx Web服务器的远程计算机发出请求,则执行对同一应用程序的所有调用,例如localhost:4200(默认为angular/cli).然后使用将这些响应重定向到您的服务器--proxy-config.
假设您的服务器的api具有所有/api前缀入口点.您需要在项目的根目录中创建名为proxy.config.json的文件,并将其配置为:
{
"/api" : {
"target" : "http://xx.xxx.xxx.xx", // Your remote address
"secure" : false,
"logLevel" : "debug", // Making Debug Logs in console
"changeOrigin": true
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您的所有http请求都将指向localhost:4200/api/.
最后,你应该通过运行来完成ng server --proxy-config proxy.config.json.
如果您发现请求中缺少某些标头,请从您的网络服务器添加标头,或者编辑您的附件http.service.ts,如下例所示:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { isNull } from 'lodash';
@Injectable()
export class HttpClientService {
private _host: string;
private _authToken: string;
private _options: RequestOptions = null;
constructor(private _http: Http, private _config: AppConfig, private _localStorageService: LocalStorageService) {
this._host = ''; // Your Host here, get it from a configuration file
this._authToken = ''; // Your token here, get it from API
}
/**
* @returns {RequestOptions}
*/
createAuthorizationHeader(): RequestOptions {
// Just checking is this._options is null using lodash
if (isNull(this._options)) {
const headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
headers.append('Authorization', this._authToken);
this._options = new RequestOptions({headers: headers});
}
return this._options;
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
get(url?: string, data?: Object): Observable<any> {
const options = this.createAuthorizationHeader();
return this._http.get(this._host + url, options);
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
post(url?: string, data?: Object): Observable<any> {
const body = JSON.stringify(data);
const options = this.createAuthorizationHeader();
return this._http.post(this._host + url, body, options);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以通过此服务执行所有api调用
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClientService } from './http.service.ts';
export class TestComponent implements OnInit {
_observable: Observable<any> = null;
constructor(private _http: HttpClientService) { }
ngOnInit() {
this._observable = this _http.get('test/')
.map((response: Response) => console.log(response.json()));
}
}
Run Code Online (Sandbox Code Playgroud)
Angular 5更新:
在app.module.ts现在,你需要更换import { HttpModule } from '@angular/http';有import { HttpClientModule } from '@angular/common/http';.
该服务有点变化:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { isNull, isUndefined } from 'lodash';
@Injectable()
export class HttpClientService {
private _host: string;
private _authToken: string;
private __headers: HttpHeaders;
constructor(private _http: HttpClient, private _config: AppConfig, private _localStorageService: LocalStorageService) {
this._host = ''; // Your Host here, get it from a configuration file
this._authToken = ''; // Your token here, get it from API
}
/**
* @returns {HttpHeaders}
*/
createAuthorizationHeader(): HttpHeaders {
// Just checking is this._options is null using lodash
if (isNull(this.__headers)) {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8')
.set('Authorization', this. _authToken || '');
this.__headers= new RequestOptions({headers: headers});
}
return this.__headers;
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
get(url?: string, data?: Object): Observable<any> {
const options = this.createAuthorizationHeader();
return this._http.get(this._host + url, {
headers : this.createAuthorizationHeader()
});
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
post(url?: string, data?: Object): Observable<any> {
const body = JSON.stringify(data);
const options = this.createAuthorizationHeader();
return this._http.post(this._host + url, body, {
headers : this.createAuthorizationHeader()
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27887 次 |
| 最近记录: |