当我单击提交按钮时,我无法获得带有node和express的响应。我对节点和表达还相当陌生。这是我试过的。你能告诉我我的代码出了什么问题吗?请指导我如何在当前html的框中获得即时响应,或者还有什么方法可以获得响应而不是异步函数?
<p class="borderBox"></p>
很难说没有看到所有的代码。但我认为第一个问题是你没有足够的防御能力来检查你的需求。某些标头并不总是出现在请求中,因此您需要提供它们未按预期到达的情况
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);
});
然后,您必须更改使用fetch()
调用的URI,以便它到达您在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')));
并将CCD_ 3放置在快递应用程序根目录下名为CCD_。文件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>
我只是把这最后一部分包括在内,因为,再一次,我看不出你是如何建立你的项目的——但这对我来说很有效。