gpt4 book ai didi

java - 带有 java servlet 的 Angular 4 http CORS No 'Access-Control-Allow-Origin'

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:48 25 4
gpt4 key购买 nike

我正在尝试做一个 http.post 但 chrome 显示以下错误:

No Access-Control-Allow-Origin.

我的 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);
}

我的 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");

最佳答案

如果您在开发时仍想使用 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
}
}

然后,您所有的 http 请求都将指向 localhost:4200/api/

最后,您应该通过运行 ng server --proxy-config proxy.config.json 来完成。

如果您注意到请求中缺少某些 header ,请从您的网络服务器添加它们或编辑您的 http.service.ts 以附加这些 header ,如本例所示:

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);
}

}

因此,您将通过此服务执行所有 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()));
}

}

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()
});
}
}

关于java - 带有 java servlet 的 Angular 4 http CORS No 'Access-Control-Allow-Origin',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44925449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com