带有汽车清单的GET方法:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/cars', (req, res) => {
res.status(200).json([{
name : 'a',
color : 'red'
},{
name : 'b',
color : 'blue'
}])
})
module.exports = app
我正在尝试将列表加载到我的HTML页面=>
单击带有load
id的按钮时,请求服务器上的cars
列表;颜色为red
的汽车被装载到ID为main
且带有tr
的表中每辆车。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>A simple app</title>
<script>
async function load(){
try{
let url ='http://localhost:8080/cars'
let response = await fetch(url)
let data = await response.json()
let table = document.getElementById('main')
table.innerHTML = ''
for (let e of data){
let rowContent = `
<tr>
<td>
${e.name}
</td>
<td>
${e.color}
</td>
</tr>`
let row = document.createElement('tr')
row.innerHTML = rowContent
//row.dataset.id = e.id
table.append(row)
}
catch(err){
console.warn(err)
}
}
}
</script>
</head>
<body>
A simple app
<table id=main></table>
<input type="button" value="add" onClick={load()} id="load"/>
</body>
</html>
没有理由之所以不能这样做,是因为
cors
,catch
块和port
。
也许您可以在下面尝试此html
:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>A simple app</title>
<script>
async function load(){
try {
let url ='http://localhost:3000/cars';
let response = await fetch(url);
let data = await response.json()
let table = document.getElementById('main');
table.innerHTML = '';
for (let e of data){
let rowContent = `
<tr>
<td>${e.name}</td>
<td>${e.color}</td>
</tr>`;
let row = document.createElement('tr')
row.innerHTML = rowContent;
table.append(row);
}
} catch(ex) {
console.log(ex);
}
}
</script>
</head>
<body>
A simple app
<table id=main></table>
<input type="button" value="add" onClick={load()} id="load"/>
</body>
</html>
现在,在您的服务器中,您可以使用此简单的服务器进行更改:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors( { origin: '*'}));
app.get('/cars', (req, res) => {
res.status(200).json([{
name : 'a',
color : 'red'
},{
name : 'b',
color : 'blue'
}])
});
app.listen(3000, () => {
console.log('Server is up');
});
我希望它能为您提供帮助。