首页 > 解决方案 > 尝试通过 onclick 函数显示来自本地 api 的数据不起作用,解决方案是什么?

问题描述

我正在尝试从我的 api 获取一些本地数据并使用按钮将其发布到浏览器控制台上,但是在按钮的功能中它不起作用,但在 onclick 功能之外它工作得很好,我什至尝试了 return 语句获取。我正在尝试这样做,所以我可以在 JS 生成的 html 表上显示所有数据。无论如何,这里是 html 代码,后面是 JS 代码:

function getUsers(){
return fetch('http://localhost:3000/users')
.then(response => response.json())
.then(json => console.log(json))
}
<button type="submit" class="btn btn-outline-light" onclick="getUsers()">Users</button>

js代码:

const express = require('express');
const app = express();
var cors = require('cors');
const bodyParser = require('body-parser');
//server stuff end

const xlsx = require('xlsx');
const file = xlsx.readFile('./testing.xlsx');
const sheet = file.Sheets['Sheet1'];
const content = xlsx.utils.sheet_to_json(sheet);
//reading xlsx file from sheet 1

app.use(bodyParser.json());
app.use(cors()); //using cors so we can call it from html file

app.get('/', function (req, res) {
 })


app.get('/Users', function (req, res) {
res.send(content);
})


app.listen(3000);

标签: javascripthtmlexpress

解决方案


你能描述一下“不起作用”是什么意思吗?onclick()-Function 是否放置在代码中的正确位置,您的开发人员控制台在单击按钮时会告诉您什么,您是否尝试过 onclick()-function 中的简单 console.log 语句来评估它是否被触发全部?

我尝试了代码(使用我自己的 url),它按预期工作。


推荐阅读