如何使用express js处理获取API请求



我想使用获取API发送请求,并希望使用Express JS处理这些请求。

我创建了server.js(express js(、index.html

signin.htmlindex.html

<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1> <center>Welcome</center> </h1>
<center> <button onclick="login()">Signin</button> </center>
</body>
<script>
function login() 
{   
fetch('./signin.html')
.then(res => console.log(res))
.catch(err => console.log(err));        
}   
</script>
</html>

server.js

const path = require('path');
const express = require('express');
const app = express();
app.get('/', (req,res) =>{
res.sendFile(path.join(__dirname,'index.html'));
}); 
app.get('/signin.html', (req,res) =>{
res.sendFile(path.join(__dirname,'signin.html'));
}); 
app.listen(8080);

我希望当用户单击"登录"按钮时,fetch apiserver.js文件发送请求,而server.jsfetch api发回响应并将响应呈现到浏览器

有可能吗?

Ajax的要点是响应由JavaScript处理,而不是通过导航到新页面来处理。

现在,可以将一个新的URL推送到历史记录中,并用新数据替换页面的整个DOM,但相对而言,这将非常复杂和繁琐。

只需使用常规链接,不涉及客户端JavaScript。

最新更新