简体   繁体   English

如何从 API 获取响应数据并从数据中编码函数以使用 node js JavaScript 获取结果

[英]How to get the response data from API and code the function from data to get the result using node js JavaScript

I think did a mess with the coding cause I'm still a newbie in node.js, javascript and vue.我认为编码有点混乱,因为我仍然是 node.js、javascript 和 vue 的新手。 I did a Currency Converter by get the data from API to get the exchange rates and did some calculation in function.我通过从 API 获取数据来获取汇率并在函数中进行了一些计算,从而完成了货币转换器。 In the 'Inspect', the console did get the exchange rates from the selected country but there is no result, did my calculation is wrong?在“检查”中,控制台确实获得了所选国家/地区的汇率,但没有结果,我的计算有误吗? or the code in the function such a mess?还是函数中的代码这么乱? I need help.我需要帮助。 So, here is my code from beginning:所以,这是我从头开始的代码:

<h1 id="main-heading">Currency Conversion</h1>
<div id="input-container">
    <span class="input-text">Convert</span>
    <select id="from-currency" v-model="fromCurrency">
        <option value="">Select currency</option>
        <option value="USD">US Dollar (USD)</option>
        <option value="MYR">Malaysia (MYR)</option>
    </select>
    <input type="number" id="from-amount" placeholder="Amount" v-model="fromAmount" />
    <span class="input-text">To</span>
    <select id="to-currency" v-model="toCurrency">
        <option value="">Select currency</option>
        <option value="USD">US Dollar (USD)</option>
        <option value="MYR">Malaysia (MYR)</option>
    </select>
    <button type="button" id="convert-btn" @click="clickConvert()">
        Convert
    </button>

cont..续..

</div>
<div id="result-container" v-if="convertClicked">
    <h2 id="result" v-if="!loading">
        <span id="from-span">{{ fromAmount }} {{ fromCurrency }}</span> =
        <span id="to-span">{{ result }} {{ toCurrency }}</span>
    </h2>
    <h2 v-else>Loading...</h2>
</div>

cont...继续...

export default {
name: 'Index',
components: {
},
data() {
    return {
        fromCurrency: '',
        toCurrency: '',
        fromAmount: 0,
        result: '',
        convertClicked: false,
        loading: false,
    }
},

the functions...功能...

methods: {
    clickConvert() {
        if (!(this.fromCurrency == '' || this.toCurrency == '' || (this.fromAmount <= 0) || this.fromCurrency == this.toCurrency)) {
            this.convertClicked = true
        }
        this.convert()
    },

function cont...功能续...

convert() {
        if (this.fromCurrency == '' || this.toCurrency == '' || (this.fromAmount <= 0) || this.fromCurrency == this.toCurrency) {
            alert("Please check your inputs and try again")
        } else {
            this.loading = true
            let uri = 'https://api.exchangeratesapi.io/latest?symbols=' + this.fromCurrency + "," + this.toCurrency;
            fetch(uri, {
                    "method": "GET",
                })
                .then((response => response.json()))
                .then(function (data) {
                    console.log(data.rates)
                    for (let [key, value] of Object.entries(data.rates))
                        var jsResult = data.rates;
                    var toCurrency = response.json(this.toCurrency);
                    var fromCurrency = response.json(this.fromCurrency);
                    var fromAmount = response.json(this.fromAmount);
                    var result = this.result;
                    var oneUnit = jsResult.toCurrency / jsResult.fromCurrency;
                    result = (oneUnit * fromAmount).toFixed(2);
                    this.loading = false
                })
                .catch(err => {
                    alert("There was a problem fetching the results. Please try again." + err)
                })
        }
    }

it turns out like this...(where can't convert the currency but can get the exchange rates) cannot get the result, pls help原来是这样...(哪里不能兑换货币但可以得到汇率)无法得到结果,请帮忙

The error is said that ReferenceError: response is not defined.错误是说 ReferenceError: response is not defined。

The second part of your promise chain will lose the context of this as you are trying to use it here.当您尝试在此处使用它时,您的承诺链的第二部分将丢失this的上下文。

                .then(function (data) {
                    console.log(data.rates)
                    for (let [key, value] of Object.entries(data.rates))
                        var jsResult = data.rates;
                    var toCurrency = response.json(this.toCurrency);
                    var fromCurrency = response.json(this.fromCurrency);
                    var fromAmount = response.json(this.fromAmount);
                    var result = this.result;
                    var oneUnit = jsResult.toCurrency / jsResult.fromCurrency;
                    result = (oneUnit * fromAmount).toFixed(2);
                    this.loading = false
                })

You can either redefine this higher in the scope of the convert() function and use the new variable, or adjust your function here to be an arrow function, which will persist the context of this .您可以在convert()函数的范围内重新定义this并使用新变量,或者将此处的函数调整为箭头函数,这将保留this的上下文。 The latter option is certainly the easier and better one.后一种选择当然是更容易和更好的选择。

.then((data) => {
    ...

You can see more on arrow functions and context here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions您可以在此处查看有关箭头函数和上下文的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM