You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js搭建翻译网页后端:如何获取用户输入词汇与目标翻译语言

How to Capture User Input for Your Node.js + Google Translate API Backend

Hey there! It looks like you’ve got the core translation functionality working with hardcoded values—great start! Let’s adjust your code to grab user input for the target word and languages instead. Here’s a step-by-step breakdown:

Step 1: Complete the Frontend to Capture User Input

First, let’s finish that translateWord() function to pull values from your HTML inputs. I’ll assume you have:

  • An input field with ID wordToTranslate for the user’s word
  • Dropdowns (or text inputs) with IDs fromLang and toLang for source/target languages

Here’s the updated frontend code:

function translateWord() {
  // Grab user input values from the page
  const word = document.getElementById("wordToTranslate").value.trim();
  const fromLang = document.getElementById("fromLang").value.trim();
  const toLang = document.getElementById("toLang").value.trim();

  // Basic validation to avoid empty requests
  if (!word || !fromLang || !toLang) {
    alert("Please fill in all translation fields!");
    return;
  }

  // Send user data to your backend
  const url = 'http://localhost:8085';
  const endpoint = '/translate';
  
  fetch(`${url}${endpoint}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ word, fromLang, toLang })
  })
  .then(response => response.json())
  .then(data => {
    // Display the result on your page (customize this to fit your UI!)
    console.log("Translated word:", data.translation);
    // Example: document.getElementById("translationOutput").textContent = data.translation;
  })
  .catch(error => {
    console.error("Translation failed:", error);
    alert("Oops, something went wrong! Try again later.");
  });
}

Step 2: Update Your Node.js Backend to Receive User Input

Assuming you’re using Express for your backend, you’ll need to parse JSON request bodies and replace hardcoded values with user-provided ones. Here’s how to adjust your endpoint:

First, install required dependencies if you haven’t already:

npm install express cors @google-cloud/translate

Then update your backend code:

const express = require('express');
const cors = require('cors');
const { Translate } = require('@google-cloud/translate').v2;

const app = express();
const port = 8085;

// Allow cross-origin requests from your frontend
app.use(cors());
// Parse JSON data from incoming requests
app.use(express.json());

// Initialize Google Translate client (use environment variables for your API key!)
const translate = new Translate({
  key: process.env.GOOGLE_TRANSLATE_API_KEY // Never hardcode your key directly!
});

// Updated endpoint to use user input
app.post('/translate', async (req, res) => {
  try {
    const { word, fromLang, toLang } = req.body;

    // Validate incoming data on the backend too
    if (!word || !fromLang || !toLang) {
      return res.status(400).json({ error: "Missing required fields: word, fromLang, toLang" });
    }

    // Call Google Translate API with user-provided values
    const [translation] = await translate.translate(word, {
      from: fromLang,
      to: toLang
    });

    // Send the translation back to the frontend
    res.json({ translation });
  } catch (error) {
    console.error("API call failed:", error);
    res.status(500).json({ error: "Failed to translate your word" });
  }
});

app.listen(port, () => {
  console.log(`Backend running on http://localhost:${port}`);
});

Key Tips to Keep in Mind

  • Security First: Store your Google Translate API key in an environment variable (use the dotenv package to manage this) instead of hardcoding it—never expose sensitive keys in your code!
  • Double Down on Validation: Adding checks for empty inputs both frontend and backend prevents unnecessary API calls and errors.
  • CORS Matters: The cors middleware fixes browser security restrictions that block requests between different ports (your frontend and backend).

Once you set this up, your users can enter their own words and select languages, and your backend will dynamically translate using those values instead of hardcoded ones!

内容的提问来源于stack exchange,提问作者TylerB56

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:23:13