Angular 如何修复错误:“引用;CORS政策“;在发出post请求时
我试图向Microsoft认知翻译服务发出POST请求,但出现以下错误:Angular 如何修复错误:“引用;CORS政策“;在发出post请求时,angular,typescript,Angular,Typescript,我试图向Microsoft认知翻译服务发出POST请求,但出现以下错误: Access to XMLHttpRequest at 'https://api.cognitive.microsofttranslator.com/post' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check
Access to XMLHttpRequest at 'https://api.cognitive.microsofttranslator.com/post' from origin 'http://localhost:4200' 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.
core.js:15723 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://api.cognitive.microsofttranslator.com/post", ok: false, …}
我在node.js中根据Microsoft提供的文档提出了类似的api POST请求:
这工作完全正常,但当我尝试使用Angular时,从今天早上开始我就一直面临同样的错误
我的最终产品将是一个选项,翻译90%的网页。现在我只想翻译一个单词来进一步理解它
如果有什么更简单的方法来翻译网站上的某些特定文本,我非常乐意转换到其他内容
到目前为止,我的代码是:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { TranslatedText } from './TranslatedText';
import { v4 as uuid } from 'uuid';
@Injectable({
providedIn: 'root'
})
export class TranslateService {
readonly request = Request;
readonly uuidv4 = uuid();
readonly subscriptionKey: string = 'MYTRANSLATIONKEY';
constructor(private http: HttpClient) { }
options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': 'de',
},
headers: {
'Ocp-Apim-Subscription-Key': this.subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': this.uuidv4.toString()
},
body: [{
'text': 'Hello World!'
}],
json: true,
};
readKey() {
if (!this.subscriptionKey) {
throw new Error('Environment variable for your subscription key is not set.')
};
}
getTranslation() {
console.log("api call gelukt");
return this.http.post('https://api.cognitive.microsofttranslator.com/post', this.options.body, this.options);
}
}
我的预期结果是在控制台中获得类似以下内容的json:
[
{
"detectedLanguage": {
"language": "en",
"score": 1.0
},
"translations": [
{
"text": "Hallo Welt!",
"to": "de"
},
]
}
]
但是我得到了前面显示的错误请与后端团队联系以处理CORS源代码。他们需要启用CORS以避免此错误。不建议在浏览器或http级别处理它。出于开发目的,您可以禁用浏览器安全性,然后使用跨组织
- 铬合金:
转到此路径并在命令提示下运行以打开浏览器。然后,您可以在http请求中调用跨组织调用。嘿,您应该阅读有关CORS()的更多信息。坦率地说,您的后端不允许来自您的域(localhost)的请求。我们决定制作一个web API来接受CORS并从那里获取数据。
[
{
"detectedLanguage": {
"language": "en",
"score": 1.0
},
"translations": [
{
"text": "Hallo Welt!",
"to": "de"
},
]
}
]