如何解决错误:在Angular中发出发布请求时出现“ CORS策略”

时间:2019-03-26 11:58:43

标签: 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: 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, …}

我从Microsoft提供的文档https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-nodejs-translate

在node.js中提出了类似的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);
  }



}

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '../translate.service';
@Component({
  selector: 'app-translate',
  templateUrl: './translate.component.html',
  styleUrls: ['./translate.component.css']
})

export class TranslateComponent implements OnInit {



  constructor(private translateService: TranslateService) { }

  ngOnInit() {
  }


  getTranslation() {

    return this.translateService.getTranslation().subscribe( (data ) => console.log(data))

  }




}

我期望的结果是在控制台中得到一个json这样的东西:

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "Hallo Welt!",
                "to": "de"
            },
        ]
    }
]

但是我越来越早看到错误了

2 个答案:

答案 0 :(得分:1)

请咨询后端团队以处理CORS来源。他们需要启用CORS以避免此错误。不建议在浏览器或http级处理它。

答案 1 :(得分:0)

出于开发目的,您可以禁用浏览器安全性,然后使用可以使用跨域。

  • 在Chrome中:

chrome.exe --user-data-dir =“ C:/ Chrome开发者会话” --disable-web-security

转到此路径并在命令提示符下运行以打开浏览器。那么您就可以调用跨组织的http请求。