簡體   English   中英

使用node.js和AJAX請求將Javascript函數移動到后端

[英]Moving Javascript function to backend with node.js and AJAX requests

如果您想在服務器端運行某些javascript函數(無論是性能還是隱藏專有代碼),那么當HTML文件訪問外部CSS和Javascript文件時,如何通過AJAX請求發送和接收數據?

例如,將函數“ secret_calculation ”移動到index.js(node.js文件)的正確方法是什么?

index.js

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {

    fs.readFile('app.html', function (err, data) {
        if (err)
        {
            console.log(err);
        }
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
    });

    fs.readFile('app.css', function (err, data) {
        if (err)
        {
            console.log(err);
        }
        res.writeHead(200, {'Content-Type': 'text/css'});
        res.write(data);
        res.end();
    });

    fs.readFile('app.js', function (err, data){
        if (err)
        {
            console.log(err);
        }
        res.writeHead(200, {'Content-Type': 'text/javascript'});
        res.write(data);
        res.end();
    });

}).listen(8000);

app.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="app.css">
  </head>

  <body>
    <input id="in_put" type="text" maxlength="3" size="5" oninput="this.value = this.value.replace(/[^0-9]/g, '');" >
    <span> x 5 = </span><span id="answer"></span>
    <br><br>
    <input type="button" id="button1" value="Calculate">

    <script src="app.js"></script>
  </body>
</html>

app.css

span
{
    color: red;
}

app.js

document.getElementById("button1").addEventListener("click", get_input);

function get_input()
{
    user_input = parseInt(document.getElementById("in_put").value);
    user_input = user_input || 0;
    ans = document.getElementById("answer");

    ans.innerHTML = secret_calculation(user_input);
}

function secret_calculation(num)
{
    var result = num * 5;    

    return result;
}

我發現與node.js的AJAX請求一個很好的例子, 在這里 ,但文章並沒有使用外部CSS和JavaScript文件

使用express,可以將路由與GET動詞綁定,並在客戶端獲得響應。 例如:

index.js

const express = require('express');
const app = express();

app.get('/your-route-here', (req, res) => {
 res.send({response: req.query.num * 5});
});

app.js

let calculatedSecret;
fetch('/your-route-here')
  .then(({data}) => {
    calculatedSecret = data.response;
});

一種方法是運行第二個http服務器,將這些功能用作服務(類似於rest API)。

為了簡單起見,我將使用express(將其簡單地包裝為http服務器的包裝器):

var http = require('http');
var fs = require('fs');
var express = require('express');
var bodyParser from 'body-parser';

// this is server code and won't get to the client if not required
function secret_calculation(num) {
    var result = num * 5;    

    return result;
}
http.createServer(function (req, res) {

    fs.readFile('app.html', function (err, data) {
        if (err) {
            console.log(err);
        }
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
    });

    fs.readFile('app.css', function (err, data) {
        if (err) {
            console.log(err);
        }
        res.writeHead(200, {'Content-Type': 'text/css'});
        res.write(data);
        res.end();
    });

    fs.readFile('app.js', function (err, data){
        if (err) {
            console.log(err);
        }
        res.writeHead(200, {'Content-Type': 'text/javascript'});
        res.write(data);
        res.end();
    });

}).listen(8000);

var apiApp = express();

// to be able to use request.body for complex parameters
apiApp.use(bodyParser.json());
apiApp.use(function (req, res, next) {
    // to restrict api calls to the ones coming from your website
    res.append('Access-Control-Allow-Origin', <url of your domain, with port>);
    res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.append('Access-Control-Allow-Headers', 'Content-Type');
    next();
});
//the list of routes your API will respond to, it is better to move this code in another file as it can be huge
apiApp.get('/secret_calculation/:number', function(req, res) {
    var num = parseInt(req.params.number, 10);
    var result = secret_calculation(num);
    res.send(JSON.stringify(result)); 
});
// define as much routes as you want like the model above, using apiApp.post if you want to post data and retrieve it with req.body...etc

// run the API server like your http server above
apiApp.listen(8001, function (err) {
    if (err) {
        return console.error(err);
    }
    console.info(`apiApp listening at ${<url to your domain, without port>}:${8001}`);
});

然后在您的應用程序中,您將能夠通過調用(使用fetch,但任何其他ajax lib都可以)從secret_calculation檢索值:

function get_input() {
    const init = {
        'GET', // or POST if you want to POST data
        headers: { 'Content-Type': 'application/json', 'Accept-Encoding': 'identity' },
        cache: 'default',
        // body: data && JSON.stringify(data), if you want to POST data through request body

    };
    var user_input = parseInt(document.getElementById("in_put").value);
    user_input = user_input || 0;
    fetch('/secret_calculation/' + user_input, init)
        .then( function(response) {

            var ans = document.getElementById("answer");
            ans.innerHTML = response;
        })
        .catch ( function(error) {
            console.log('something bad happened:', error);
        });
}

Express JS參考

使用Express在5分鍾內創建REST API的簡單教程(類似於以上內容)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM