首页 > 解决方案 > 使用来自节点 js 的 ajax 变量

问题描述

我正在尝试使用节点 js 中的 ajax 变量,但我不知道如何使用。

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

app.listen(8080, function() {
    console.log('Listening on 8080.');
});

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/search.html');
    console.log('req.params:', req.params); //req.params: {}
});

上面的代码是我的 server.js

<script>
    function postData() {
        var country = document.getElementById("Country").value;
        console.log(country);
        $.ajax({
            type: "GET",
            url: 'http://localhost:8080/',
            data: country,
            dataType:'text',
            success: function(data) {
                console.log('success data: ', data);
            }
        });
    }
</script>

搜索.html

标签: javascriptnode.js

解决方案


假设您要尝试country在 Ajax 调用中传递值,然后在服务器上访问该值,那么您需要将国家/地区放入 URL 中,以便您的服务器可以从 URL 中获取它。

有了$.ajax()你可以传递一个对象然后jQuery会自动生成一个查询字符串的形式key=value。或者,您可以直接将其作为路径的一部分添加到 URL。以下是您将其作为查询字符串的方式:

function postData() {
    var country = document.getElementById("Country").value;
    console.log(country);
    $.ajax({
        type: "GET",
        url: 'http://localhost:8080/',
        data: {country: country},
        success: function(data) {
            console.log('success data: ', data);
        }
    });
}

这将创建一个 URL,例如:

http://localhost:8080/?country=USA

然后,在您的服务器上,您可以使用req.query.country来获取值:

app.get('/', function(req, res) {
    console.log(req.query.country);
    res.sendFile(__dirname + '/search.html');
});

您还可以创建 URL,例如:

http://localhost:8080/usa

并且,向该 URL 发出请求。要在您的服务器上接收它,您可以这样做:

app.get('/:country', function(req, res) {
    console.log(req.params.country);
    res.sendFile(__dirname + '/search.html');
});

请注意,这就是我所说的通配符路由,因为它匹配任何可能干扰您在服务器上使用其他顶级 URL 的能力的顶级路径。我建议不要使用顶级通配符 URL。您可以像这样添加路径前缀:

http://localhost:8080/country/usa

然后使用这个:

app.get('/country/:country', function(req, res) {
    console.log(req.params.country);
    res.sendFile(__dirname + '/search.html');
});

然后,它不会干扰您的服务器可能想要使用的其他顶级 URL。


推荐阅读