简体   繁体   中英

How to handle fetch API request with express js

I want to send request using fetch API and want to handle those request with Express JS .

I have created server.js (express JS), index.html (home page) and signin.html (signin page).

index.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);

I want when user click the Sign in button, fetch api send a request to server.js file and server.js send back response to fetch api and render the response to the browser .

Is it possible?

The entire point of Ajax is that the response is handled by your JavaScript and not by navigating to a new page.

Now, you could push a new URL into the history and replace the entire DOM of the page with the new data, but it would be, in relative terms, hugely complex and fiddly.

Just use a regular link and don't involve client-side JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM