I try to use a very basic API call from Windows Azure to translate some texts. They gives a quickstart example code.
I try this code and it works pretty well. The text Hello world
is translated into deutch and italian.
I removed my personal subscription key.
Here is the sample:
const request = require('request');
const uuidv4 = require('uuid/v4');
const subscriptionKey = '........';
let options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': ['de', 'it']
},
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: [{
'text': 'Hello World!'
}],
json: true,
};
request(options, function(err, res, body){
console.log(JSON.stringify(body, null, 4));
});
It looks like this code is a server side library for node
. Now I need to integrate this code into my [aurelia][2] application. So I think of using the aurelia-fetch-client
to replace the request
method. I use the Aurelia CLI.
Here is what I did:
Added in package.json:
"dependencies": {
....
"@types/uuidv4": "^2.0.0",
...
"uuidv4": "^4.0.0",
}
Added in aurelia.json:
"dependencies": [
...
"uuidv4"
]
Run npm install
inside my console.
Created a test page:
import { HttpClient, json } from 'aurelia-fetch-client';
import { autoinject } from 'aurelia-framework';
import * as uuidv4 from 'uuidv4';
import secret from '../secret';
@autoinject
export class Translator {
constructor(httpClient: HttpClient) {
this.httpClient = httpClient;
}
private httpClient: HttpClient;
private translate(from, to, html) {
debugger;
var init: RequestInit =
{
method: 'POST',
//mode: 'no-cors',
headers: {
'Ocp-Apim-Subscription-Key': secret.translatorKey,
'Content-type': 'application/json',
//'Content-Type': 'application/x-www-form-urlencoded',
'X-ClientTraceId': uuidv4().toString()
},
credentials: 'same-origin',
body: $.param({
'api-version': '3.0',
'from': 'en',
'to': 'fr',
'text': '<b>Hello World!</b>' })
//body: json({ 'text': '<b>Hello World!</b>' })
};
this.httpClient.fetch(`https://api.cognitive.microsofttranslator.com/`, init)
.then((result) => {
debugger;
})
.catch((error) => {
debugger;
});
}
The trick is to be able to get the options passed to the request
of the sample code and adjust it to the aurelia-fetch-client
. I did not succeed.
Unfortunately I always get the error below:
Access to fetch at 'https://api.cognitive.microsofttranslator.com/' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Any suggestions ?
https://api.cognitive.microsofttranslator.com/
is apparently a 3xx redirect. Check the Location response header in the response. You can use the Network pane in browser devtools to view it. See what URL the response is trying to redirect you to. – sideshowbarker