我是 Angular 新手,在我的一门课上遇到了这种情况:
我有一个简单的 Angular 应用程序在我的 localhost:4200 上运行,我想从女巫那里向 RESTHEART 本地 API 发帖。
正如我从 RESTHEART 教程https://restheart.org/learn/tutorial/中获得的那样,我安装了 Docker 并下载了 docker-compose.yml,运行它时,我在 localhost:8080 中找到它(我相信这部分没问题)
我尝试了一些关于 CORS 的信息,但我没有找到如何在 RESTHEART api 中启用它。我在 RESTHEART 上获得了一些信息,说它支持 CORS,但这不是一个非常清楚的文本。
当我尝试发布到https://beta.mrest.io/demo/messages时我没有问题,女巫不是本地主机
另外,我按照此页面中的说明获取了 api https://restheart.org/learn/setup/,但取消注释“- ./etc:/opt/restheart/etc:ro”行除外,因为它生成了关于无效端口的错误(如果你们认为有必要,我稍后会添加错误)
这是我的 ComponentService,我从那里拍摄发布请求(我无法在此处对其进行格式化以以体面的方式显示代码,对此我很抱歉)
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs';
const host = 'http://localhost:8080/db/coll';
// const host = 'https://beta.mrest.io/demo/messages';
@Injectable()
export class ContatoComponentService {
constructor(private http: Http) {
}
enviarContato(contatoForm: any): Observable<Response> {
const headers = new Headers();
headers.append('key', 'demo');
const nomeCompleto = contatoForm.nomeCompleto;
const email = contatoForm.contato.email;
const mensagem = 'Mensagem de teste'; // contatoForm.mensagem;
console.log('nomeCompleto', nomeCompleto);
console.log('email', email);
console.log('mensagem', mensagem);
return this.http.post(host, {email: email, from: nomeCompleto, message: mensagem}, { headers: headers});
}
}
但是当我向 api 发出 post 请求时,我收到此错误:“从源 ' http: // localhost:4200 ' 访问 XMLHttpRequest 已被 CORS 策略阻止: 预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段键"