简体   繁体   English

从客户端脚本获取值并覆盖服务器端脚本

[英]Get value from client side script and override server side script

Below are my server side and client side JavaScript files. 以下是我的服务器端和客户端JavaScript文件。 I have hard coded queryObject in server side script I can display the body in client-side. 我在服务器端脚本中有硬编码的queryObject我可以在客户端显示正文。 The problem is how to get value from client side for queryObject variable in server side and override the existing values. 问题是如何从客户端获取服务器端queryObject变量的值并覆盖现有值。 In short, current program converts USD to GBP as I hard-coded it. 简而言之,当我编写硬编码时,当前程序将USD转换为GBP。 I want a way to access queryObject from client side and give my own values. 我想要一种从客户端访问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;
    }
  });
});

SOLUTION: 解:

In order to modify any values in server, you have to send appropriate HTTP method (eg: POST) with appropriate data in it. 为了修改服务器中的任何值,您必须发送适当的HTTP方法(例如:POST),并在其中包含适当的数据。 And let the server handle the request to change the content of object to make an API call from there. 并让服务器处理请求以更改对象的内容以从那里进行API调用。

I made some changes in your code for demonstration and install 'cors', 'body-parser' module and other missing modules to make it run. 我对您的代码进行了一些更改以进行演示,并安装'cors','body-parser'模块和其他缺少的模块以使其运行。

HTML: 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>

NodeJS: 的NodeJS:

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);
});

Sample output: 样本输出:

在此输入图像描述

You'll code in client-side to send a request to server-side containing the query object. 您将在客户端编码以向包含查询对象的服务器端发送请求。 And on the server-side, you pick up your query object. 在服务器端,您可以选择查询对象。

There are so many ways of doing this. 有很多方法可以做到这一点。

  1. Using a GET request with parameters - On the server-side your query object will be available at res.query.params 使用带参数的GET请求 - 在服务器端,您的查询对象将在res.query.params可用
  2. Using a POST request - On the server side you will want to use the body-parser plugin for parsing your response body and hence, your data will be available at res.body 使用POST请求 - 在服务器端,您将需要使用正文解析器插件来解析您的响应正文,因此,您的数据将在res.body可用

Read on body parser 阅读身体解析器

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

相关问题 将Java Script的返回值获取到服务器端 - Get the returned value of Java Script to server side 通过客户端脚本与服务器进行GAS HTML服务通信 - GAS HTML service communication with server from client side script 在 Google Apps 脚本中从服务器到客户端进行通信 - Communicate from server to client side in Google Apps script Java脚本从服务器(asp.net)获取数据并将其保存在本地存储(客户端)中 - Java Script get data from server (asp.net) and save it in local storage (client side) 具有 Google Apps 脚本值的服务器端和客户端通信函数 - Server Side and Client Side communications Functions with values at Google Apps Script Opa:它如何识别服务器端或客户端脚本 - Opa: how does it identify server-side or client side script 如何在服务器端ASP脚本中获取客户端dateTime? - How to get client-side dateTime in server-side ASP script? 在用户控件中将服务器端数据获取到客户端脚本的最佳方法 - Best way to get server-side data to client-side script in usercontrol 从客户端Java脚本在ASP.NET中调用服务器端事件处理程序 - Calling server side event handler in asp.net from client side java script 如何将数据从客户端表单输入传输到服务器端Nodejs脚本? - How do I transfer data from a client-side form input to a server-side Nodejs script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM