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

如何解决JavaScript项目中链接内美元符号无法使用的问题?

问题解决:链接内美元符号无法正常解析
  • 问题根源:你当前用单引号(')包裹endpoint字符串,ES6的变量插值语法${变量名}仅在**反引号()**包裹的模板字符串中才会被解析,单引号会将${this.apikey}`作为纯文本直接带入URL,导致API密钥无法正确传递。
  • 修正代码:
Translate.prototype.translateWord = function (callback) {
    // 把单引号换成反引号,让模板字符串生效
    const endpoint = `https://google-translate1.p.rapidapi.com/language/translate/v2/languages?key=${this.apikey}`;
    // 补充XHR请求逻辑示例
    this.xhr.open('GET', endpoint, true);
    this.xhr.setRequestHeader('X-RapidAPI-Key', this.apikey);
    this.xhr.setRequestHeader('X-RapidAPI-Host', 'google-translate1.p.rapidapi.com');
    
    this.xhr.onload = function() {
        if(this.status === 200) {
            callback(null, JSON.parse(this.responseText));
        } else {
            callback(`请求错误:${this.status}`, null);
        }
    };
    
    this.xhr.send();
};

额外提示:RapidAPI的Google Translate接口通常要求在请求头中传递API密钥,而非URL参数,上述代码已补充请求头设置,你可根据实际接口文档调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:22:01