Help

Script processing error: Handling redirects

Topic Labels: Automations
76 0
cancel
Showing results for 
Search instead for 
Did you mean: 
anton2
4 - Data Explorer
4 - Data Explorer

Hello,

I am trying to trigger a script when 'Language' field of given record is empty (record=domain).

I want the script to fetch domain's language. I first ask script to convert domain to URL, since the API call works best with exact URL and not domain.

But the problem is that script can not properly handle permanent redirects. I 've tried handle permanent redirects by trying to convert the domain to a URL using 'https://www' + domainId + '/', but that does not work. I am getting this error:

 

"Error processing https://viberate.com/: Response status was 301 'Moved Permanently' but redirect mode was set to 'error'"

 

How do I solve this?

My script:

 

// Get input variables from previous automation steps
let inputConfig = input.config();
let airtableRecordId = inputConfig.AirtableRecordID;
let domainId = inputConfig.DomainID;

// Set up the table
let table = base.getTable('Master Draft');

// Convert domain ID to URL
let url = 'https://' + domainId + '/';

const apiKey = '123456789';
const apiUrl = 'https://translation.googleapis.com/language/translate/v2/detect';

try {
    // Fetch content from URL
    let response = await fetch(url);
    if (response.status === 301 || response.status === 308) {
        // Handle permanent redirect
        url = 'https://www.' + domainId + '/';
        response = await fetch(url);
    }
    let text = await response.text();

    // Prepare request to Google Cloud Translation API
    let requestBody = JSON.stringify({
        q: text.substring(0, 150) // Limit to first 150 characters
    });

    let detectResponse = await fetch(`${apiUrl}?key=${apiKey}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: requestBody
    });

    let result = await detectResponse.json();

    if (result.data && result.data.detections && result.data.detections[0]) {
        let detectedLanguage = result.data.detections[0][0].language;
        
        // Update the record with detected language
        await table.updateRecordAsync(airtableRecordId, {
            'Language': detectedLanguage
        });

        // Set output for use in subsequent automation steps
        output.set('DetectedLanguage', detectedLanguage);
        
        console.log(`Language detected for ${domainId}: ${detectedLanguage}`);
    } else {
        console.log(`Unable to detect language for ${domainId}`);
    }
} catch (error) {
    console.error(`Error processing ${url}: ${error.message}`);
}

 

 

0 Replies 0