javascript - 单击提交按钮后,如何通过快速节点在当前窗口中的框中获取结果?
问题描述
当我单击提交按钮时,我无法通过 node 和 express 获得响应。我对节点和表达相当陌生。这是我尝试过的。你能告诉我我的代码有什么问题吗?请指导我如何在当前 html 的框中获得即时响应,或者有什么其他方式来获得响应而不是异步功能?
<p class="borderBox"></p>
解决方案
没有看到你所有的代码就很难说。但我认为第一个问题是你没有足够防御性地检查你的 req.headers kvps。某些标头并不总是出现在请求中,因此您需要提供它们未按预期到达的情况
if (req['x-forwarded-for']) {
var ip = req['x-forwarded-for'].split(',')
或者
req['x-forwarded-for'] = req['x-forwarded-for'] || ''
更新
根据您提供的代码判断,首先对您的 server.js 代码进行以下更改:
app.get('/headers', function(req, res) {
if (req.headers['x-forwarded-for'])
var ip = req.headers["x-forwarded-for"].split(',')[0];
if (req.headers['accept-language'])
var lang = req.headers['accept-language'].split(',')
if (req.headers['user-agent'])
var sys = req.headers['user-agent'].match(/\((.+?)\)/)[1]
var obj = {
"IP Address": ip,
"Language" : lang,
"Operating System": sys
}
// res.json(obj);
res.set('Content-Type', 'application/json');
res.status(200).send(obj);
});
然后,您必须更改您调用的 URI,fetch()
以便它到达您在上面指定的端点app.get()
(即“/headers”)。我在端口 3000 上使用 localhost。
$("#submit").submit(async function(event) {
event.preventDefault();
// const response = await fetch(window.location.href);
const response = await fetch('http://localhost:3000/headers');
const data = await response.json();
document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
});
最后,我对您的项目设置了解不多,但这是我通过使用 express 提供 index.html 文件的方法
app.use(express.static(path.join(__dirname, 'public')));
并放置在以 express 应用程序的根目录index.html
命名的目录中。/public
该文件index.html
如下:
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<p>
Please click to get the IP address, language, and operating system for your
device.
</p>
<form id="submit">
<button type="submit">Submit</button>
</form>
<p class="borderBox"> </p>
<script>
$("#submit").submit(async function(event) {
event.preventDefault();
// const response = await fetch(window.location.href);
const response = await fetch('http://localhost:3000/headers');
const data = await response.json();
document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
});
</script>
我只包括最后一部分,因为我看不出你是如何设置项目的——但这对我有用。
推荐阅读
- c - STM32 DMA 导致错误导致 PWM 定时器出现奇怪行为
- intellij-idea - 安装 IntelliJ IDEA 后打开现有项目
- r - Shiny 中的列联表,可选择输入组或总值并验证输入
- database - 查询以计算并返回另一个集合的平均评分?
- javascript - WEBPACK_IMPORTED_MODULE_3 CollectionGroup 不是函数-firebase 集合组查询嵌套数据
- node.js - 使用 Node js 从 Shopify Graphql 查询响应中获取键:值对
- php - Laravel 路由出现故障
- firebase - Next-auth Google 身份验证和 Firebase 适配器
- excel - 通过 Office.JS 获取 Excel 单元格绑定的问题
- c# - 从旧的excel文件中提取PNG问题?