javascript - 使用来自节点 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
解决方案
假设您要尝试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。
推荐阅读
- sql - 使用嵌套对象更新 SQL Json 字段中的属性
- json - 用户登录时如何显示我的 api 响应?
- code-generation - Simulink 代码生成:来自 Function Caller 模块的函数存根及其返回值/参数
- python - 参数替换后让sqlite3进行查询优化
- python - Asyncio.sleep 阻塞了函数的其余部分
- angular - valueGetter 未反映在 rowdata ag-gird 中
- audio - 更改所有幻灯片的音频播放设置
- python - ConnectionRefusedError: [WinError 10061] 无法建立连接,因为目标机器在使用 Python 时在 VS Code 上主动拒绝了它
- java - 休眠不从数据库中检索数据
- c# - 如果当前行以空格开头,则删除前面的 CRLF