Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从客户端脚本获取值并重写服务器端脚本_Javascript_Node.js_Express - Fatal编程技术网

Javascript 从客户端脚本获取值并重写服务器端脚本

Javascript 从客户端脚本获取值并重写服务器端脚本,javascript,node.js,express,Javascript,Node.js,Express,下面是我的服务器端和客户端JavaScript文件。我在服务器端脚本中硬编码了queryObject,我可以在客户端显示主体。 问题是如何从客户端获取服务器端queryObject变量的值,并覆盖现有值。 简而言之,当前程序将美元转换为英镑,正如我硬编码的那样。我想要一种从客户端访问queryObject并给出我自己的值的方法 //=====================Server Side Script========================// var request = re

下面是我的服务器端和客户端JavaScript文件。我在服务器端脚本中硬编码了queryObject,我可以在客户端显示主体。 问题是如何从客户端获取服务器端queryObject变量的值,并覆盖现有值。 简而言之,当前程序将美元转换为英镑,正如我硬编码的那样。我想要一种从客户端访问queryObject并给出我自己的值的方法

//=====================Server Side Script========================//

var request = require('request');
const path = require("path");
const express = require("express");
const app = express();
// const hbs = require("hbs");

const port = process.env.PORT || 3000;

const pathPublic = path.join(__dirname, "../public");
const pathView = path.join(__dirname, "../templates/views");
app.set("view engine", "hbs");
app.set("views", pathView);
app.use(express.static(pathPublic));

app.get("", (req, res) => {
  res.render("home", {
    title: "Currency Converter"
  });  
});


app.get("/currency", (req, res) => {
    const uri = "https://currency-exchange.p.rapidapi.com/exchange?",
    headers={
    'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
    'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
    }
    const queryObject  = {
        q: 1,
        from: 'USD',
        to: 'GBP'
        };

    request({
        url:uri,
        qs:queryObject,
        headers: headers
    },
function (error, response, body) {
    if (error) {
        console.log('error:', error); // Print the error if one occurred

    } else if(response && body) {
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        res.json({'body': body}); // Print JSON response.
    }
    })
});

app.listen(port, () => {
console.log("Server is running on port " + port);
});

//=====================Client Side Script========================//

const currency = document.querySelector("#currency");
const text1= document.querySelector(".text1");
const text2= document.querySelector(".text2");
const text3= document.querySelector(".text3");
const Form = document.querySelector("form");

function refreshPage() {
  window.location.reload();

}

Form.addEventListener("submit", e => {
    e.preventDefault();


fetch("http://localhost:3000/currency").then(response => {
  response.json().then(data => {
    if (data.error) {
      console.log(data.error);
    } else {
      currency.textContent = data.body;
    }
  });
});

您将在客户端编写代码,向服务器端发送包含查询对象的请求。 在服务器端,选择查询对象

有很多方法可以做到这一点

  • 使用带参数的GET请求-在服务器端,您的查询对象将在
    res.query.params
  • 使用POST请求-在服务器端,您需要使用插件解析响应正文,因此,您的数据将在
    res.body

  • 解决方案:

    <!DOCTYPE html>
    <html>
    
    <body>  
        <div id="currencyType">
            <select id="fromCurrency">
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
            </select>
            <select id="toCurrency">
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
            </select>
        </div>
        <button type="button" id="getCurrency">Get Currency</button>
        <div id="currency" name="currency" type="text"></div>
    
    <script>
        const currency = document.querySelector("#currency");
        const btn = document.getElementById("getCurrency");
        function refreshPage() {
            window.location.reload();
        }
        btn.addEventListener("click", e => {
            var fromCurrency = document.getElementById("fromCurrency");
            fromCurrency = fromCurrency.options[fromCurrency.selectedIndex].value;
            var toCurrency = document.getElementById("toCurrency");
            toCurrency = toCurrency.options[toCurrency.selectedIndex].value;
            var data = {
                fromCurrency: fromCurrency,
                toCurrency: toCurrency
            };
            // calls the API with POST method with data in it
            fetch("http://localhost:3000/currency", {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            }).then(response => {
                response.json().then(data => {
                    if (data.error) {
                      console.log(data.error);
                    } else {
                      currency.textContent = "1 " + fromCurrency + " = " + data.body + " " + toCurrency;
                    }
                });
            });
        });
    </script>
    </body>
    </html>
    
    var request = require('request');
    const path = require("path");
    const express = require("express");
    const app = express();
    var cors = require('cors')
    // const hbs = require("hbs");
    var bodyParser = require('body-parser');
    
    const port = process.env.PORT || 3000;
    
    const pathPublic = path.join(__dirname, "public");
    const pathView = path.join(__dirname, "templates/views");
    app.set("view engine", "hbs");
    app.set("views", pathView);
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.use(express.static(pathPublic));
    app.use(cors())
    
    
    app.get("", (req, res) => {
      res.render("home", {
        title: "Currency Converter"
      });  
    });    
    app.post("/currency", (req, res) => {
        console.log(req.body);
        const uri = "https://currency-exchange.p.rapidapi.com/exchange?",
        headers={
            'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
            'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
        }
        const queryObject  = {
            q: 1,
            from: req.body.fromCurrency,
            to: req.body.toCurrency
        };
        console.log(queryObject);
        request({
            url:uri,
            qs:queryObject,
            headers: headers
        }, function (error, response, body) {
            if (error) {
                console.log('error:', error); // Print the error if one occurred
    
            } else if(response && body) {
                console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                res.json({'body': body}); // Print JSON response.
            }
            })
        });
    app.listen(port, () => {
    console.log("Server is running on port " + port);
    });
    
    为了修改服务器中的任何值,您必须发送包含适当数据的适当HTTP方法(例如:POST)。并让服务器处理更改对象内容的请求,以便从此处进行API调用

    我在您的演示代码中做了一些更改,并安装了“cors”、“body parser”模块和其他缺失的模块使其运行

    HTML:

    <!DOCTYPE html>
    <html>
    
    <body>  
        <div id="currencyType">
            <select id="fromCurrency">
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
            </select>
            <select id="toCurrency">
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
            </select>
        </div>
        <button type="button" id="getCurrency">Get Currency</button>
        <div id="currency" name="currency" type="text"></div>
    
    <script>
        const currency = document.querySelector("#currency");
        const btn = document.getElementById("getCurrency");
        function refreshPage() {
            window.location.reload();
        }
        btn.addEventListener("click", e => {
            var fromCurrency = document.getElementById("fromCurrency");
            fromCurrency = fromCurrency.options[fromCurrency.selectedIndex].value;
            var toCurrency = document.getElementById("toCurrency");
            toCurrency = toCurrency.options[toCurrency.selectedIndex].value;
            var data = {
                fromCurrency: fromCurrency,
                toCurrency: toCurrency
            };
            // calls the API with POST method with data in it
            fetch("http://localhost:3000/currency", {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            }).then(response => {
                response.json().then(data => {
                    if (data.error) {
                      console.log(data.error);
                    } else {
                      currency.textContent = "1 " + fromCurrency + " = " + data.body + " " + toCurrency;
                    }
                });
            });
        });
    </script>
    </body>
    </html>
    
    var request = require('request');
    const path = require("path");
    const express = require("express");
    const app = express();
    var cors = require('cors')
    // const hbs = require("hbs");
    var bodyParser = require('body-parser');
    
    const port = process.env.PORT || 3000;
    
    const pathPublic = path.join(__dirname, "public");
    const pathView = path.join(__dirname, "templates/views");
    app.set("view engine", "hbs");
    app.set("views", pathView);
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.use(express.static(pathPublic));
    app.use(cors())
    
    
    app.get("", (req, res) => {
      res.render("home", {
        title: "Currency Converter"
      });  
    });    
    app.post("/currency", (req, res) => {
        console.log(req.body);
        const uri = "https://currency-exchange.p.rapidapi.com/exchange?",
        headers={
            'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
            'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
        }
        const queryObject  = {
            q: 1,
            from: req.body.fromCurrency,
            to: req.body.toCurrency
        };
        console.log(queryObject);
        request({
            url:uri,
            qs:queryObject,
            headers: headers
        }, function (error, response, body) {
            if (error) {
                console.log('error:', error); // Print the error if one occurred
    
            } else if(response && body) {
                console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                res.json({'body': body}); // Print JSON response.
            }
            })
        });
    app.listen(port, () => {
    console.log("Server is running on port " + port);
    });
    
    样本输出:

    <!DOCTYPE html>
    <html>
    
    <body>  
        <div id="currencyType">
            <select id="fromCurrency">
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
            </select>
            <select id="toCurrency">
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
            </select>
        </div>
        <button type="button" id="getCurrency">Get Currency</button>
        <div id="currency" name="currency" type="text"></div>
    
    <script>
        const currency = document.querySelector("#currency");
        const btn = document.getElementById("getCurrency");
        function refreshPage() {
            window.location.reload();
        }
        btn.addEventListener("click", e => {
            var fromCurrency = document.getElementById("fromCurrency");
            fromCurrency = fromCurrency.options[fromCurrency.selectedIndex].value;
            var toCurrency = document.getElementById("toCurrency");
            toCurrency = toCurrency.options[toCurrency.selectedIndex].value;
            var data = {
                fromCurrency: fromCurrency,
                toCurrency: toCurrency
            };
            // calls the API with POST method with data in it
            fetch("http://localhost:3000/currency", {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            }).then(response => {
                response.json().then(data => {
                    if (data.error) {
                      console.log(data.error);
                    } else {
                      currency.textContent = "1 " + fromCurrency + " = " + data.body + " " + toCurrency;
                    }
                });
            });
        });
    </script>
    </body>
    </html>
    
    var request = require('request');
    const path = require("path");
    const express = require("express");
    const app = express();
    var cors = require('cors')
    // const hbs = require("hbs");
    var bodyParser = require('body-parser');
    
    const port = process.env.PORT || 3000;
    
    const pathPublic = path.join(__dirname, "public");
    const pathView = path.join(__dirname, "templates/views");
    app.set("view engine", "hbs");
    app.set("views", pathView);
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.use(express.static(pathPublic));
    app.use(cors())
    
    
    app.get("", (req, res) => {
      res.render("home", {
        title: "Currency Converter"
      });  
    });    
    app.post("/currency", (req, res) => {
        console.log(req.body);
        const uri = "https://currency-exchange.p.rapidapi.com/exchange?",
        headers={
            'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
            'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
        }
        const queryObject  = {
            q: 1,
            from: req.body.fromCurrency,
            to: req.body.toCurrency
        };
        console.log(queryObject);
        request({
            url:uri,
            qs:queryObject,
            headers: headers
        }, function (error, response, body) {
            if (error) {
                console.log('error:', error); // Print the error if one occurred
    
            } else if(response && body) {
                console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                res.json({'body': body}); // Print JSON response.
            }
            })
        });
    app.listen(port, () => {
    console.log("Server is running on port " + port);
    });
    

    很高兴它对您有所帮助。:)