js with translation API, require is not defined, javascript does not work

Asked 2 years ago, Updated 2 years ago, 84 views

Please refer to this article in Qiita
I'm thinking of putting in the Microsoft Translator API.
Reference Articles

'use strict';

var http=require('http');
var https=require('https');
varqs=require('querystring');

getAccessToken(function(token){
    translate(token, 'text you want to translate', function(translated){
        console.log(translated);
    });
});

function getAccessToken(callback){
    var body=';
    var request = https.request({
        host: 'datamarket.accesscontrol.windows.net',
        path: '/v2/OAuth2-13',
        method: 'POST'
    }, function(res){
        res.setEncoding('utf8');
        res.on('data', function(chunk){
            body+=chunk;
        }).on('end', function(){
            varresData=JSON.parse(body);
            callback(resData.access_token);
        });
    }).on('error', function(err){
        console.log(err);
    });
    vardata = {
        'client_id': 'String set to client ID',
        'client_secret': 'Customer Secret String',
        'scope': 'http://api.microsofttranslator.com',
        'grant_type': 'client_credentials'
    };

    req.write(qs.stringify(data)));
    req.end();
}

function translate (token, text, callback) {
    var options='appId=Bearer'+token+'&to=en&text='+text+
            '&oncomplete=translated';
    var body=';
    var request = http.request({
        host: 'api.microsofttranslator.com',
        path: '/V2/Ajax.svc/Translate?' + qs.escape(options),
        method: 'GET'
    }, function(res){
        res.setEncoding('utf8');
        res.on('data', function(chunk){
            body+=chunk;
        }).on('end', function(){
            event(body);
        });
    }).on('error', function(err){
        console.log(err);
    });

    req.end();

    function translated(text){
        callback(text);
    }
}

If you add the above code to the js file,

with console error
require is not defined

appears.

Other methods have also failed to respond to console.log due to this problem.

The Qiita article didn't even mention the html file, but
Do I need to declare something in advance?

Thank you for your cooperation.

javascript jquery

2022-09-30 21:00

2 Answers

It's not a JavaScript running on the browser, but a JavaScript running on the server side.
JavaScript runs on the server side, so you need an environment to run on the server side.

Try searching by commonJS or node.js keywords.I think a lot of helpful sites will be a hit.


2022-09-30 21:00

It may be faster to find another sample code because it is not a code that can be operated by a browser.For example, Try 38th Microsoft Translator: Try it! Windows Live SDK/API|gihyo.jp…Technical Critics


2022-09-30 21:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.