【问题标题】:Why is my variable not altering after changing once为什么我的变量在更改一次后没有改变
【发布时间】:2019-07-11 10:13:25
【问题描述】:

我正在制作一个简单的 Web 应用程序,它使用 API 获取单词的定义。 API 密钥肯定没有任何问题,因为应用程序半工作 - 一旦我第一次搜索一个单词,它会返回一个结果,但是,在第二次尝试之后,定义不会改变(定义匹配第一个单词而不是最新的单词)。

我认为它与范围和常量有关,但我已经尝试过了(将 var 更改为 let 或 const)。我在网上读到回调函数是异步的,但我认为这根本不是问题。

app.get('/definition/:word', (req, res) => {
    if (word !== req.params.word) {
        console.log("If statement");
        word = req.params.word;
        console.log(word);
        word = word.toLowerCase();
    }

    options.path += '/' + language_code + '/' + word + '?fields=definitions' +
    '&strictMatch=true';

    url += options.path;
    console.log(options.path);

    request(url, options, (error, response, body) => {
        if (error) {
            res.redirect('/error');
        } else {
            let statusCode = (response.statusCode);
            console.log(statusCode);
            if (statusCode === 200) {
                let data = JSON.parse(body);
                console.log(definition);
                definition = String(data.results[0].lexicalEntries[0].entries[0].senses[0].definitions);
                console.log(definition);
                res.render('definition', {
                    wordTitle: word,
                    definitions: definition
                });
            } else {
                res.redirect('/error');
            }

        }
    });
});

app.post('/', (req, res) => {

    console.log("Post");


    word = String(req.body.Word);
    word = word.toLowerCase();

    console.log(word);

    res.redirect('/definition/' + word);
});


编辑 1: 完整的 index.js 源代码: https://github.com/NikodemBieniek/dictionary/blob/myfeature/server/index.js

【问题讨论】:

  • 你描述的不是很好,什么变量没有改变? word?从我在您的代码中看到的内容,您在任何地方都使用全局变量。不要在任何地方使用全局变量,仅使用let 和const。这意味着您将无法更改全局 word 变量,这是正确的做法。如果您想要使用 cookie、Web 存储或数据库之类的东西,API 不应该保存任何类型的用户状态。 TL;博士;没有错误的不是代码的一部分,而是您的所有代码。不要使用全局变量。
  • 对不起,我没有显示我的完整代码:github.com/NikodemBieniek/dictionary/blob/myfeature/server/…
  • 我已经使用 let 在顶部声明了变量
  • 不变的变量是'definition'。变量“单词”每次都会改变,但定义不会改变
  • 您是否真的检查过data.results[0].lexicalEntries[0].entries[0].senses[0].definitions 不等于该值?也许也可以调试/记录它

标签: node.js express callback request


【解决方案1】:

我认为问题出在下面的代码行

    options.path += '/' + language_code + '/' + word + '?fields=definitions' +
    '&strictMatch=true';

所以当您第一次进行 API 调用并将参数作为“XYZ”传递时 option.path 中的值将是

/en-gb/xyz?fields=definition&strictMatch=true

第二次调用 API 并将参数作为“PQR”传递时,option.path 中的值将是

/en-gb/xyz?fields=definition&strictMatch=true/en-gb/pqr?fields=definition&strictMatch=true

因为你正在做字符串连接。

可能的解决办法是


app.get('/definition/:word', (req, res) => {
    if (word !== req.params.word) {
        console.log("If statement");
        word = req.params.word;
        console.log(word);
        word = word.toLowerCase();




    }
   const options = {
    host: 'https://od-api.oxforddictionaries.com',
    port: '443',
    path: '/api/v2/entries',
    method: "GET",
    headers: {
        'app_id': process.env.APP_ID,
        'app_key': process.env.APP_KEY,
    }
};

    options.path += '/' + language_code + '/' + word + '?fields=definitions' +
    '&strictMatch=true';

    let url = `${options.host}${options.path}`;

    request(url, options, (error, response, body) => {
        if (error) {
            res.redirect('/error');
        } else {
            let statusCode = (response.statusCode);
            console.log(statusCode);
            if (statusCode === 200) {
                let data = JSON.parse(body);
                definition = String(data.results[0].lexicalEntries[0].entries[0].senses[0].definitions);
                res.render('definition', {
                    wordTitle: word,
                    definitions: definition
                });
            } else {
                res.redirect('/error');
            }

        }
    });
});


删除第 12 行和第 26 行声明的选项和 URL

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 2021-10-31
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多