1

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?

2
  • Use a validator. There is no <center> any more. We've had CSS for presentation for over two decades. Commented Aug 7, 2020 at 15:21
  • You could try shifting the fetch api code to the server side (button enclosed in a form) or an <a> tag Commented Aug 7, 2020 at 15:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually my plan is to send authentication token with every DB query request and verify the token first then perform the query.
Use a cookie for that if you are dealing with whole pages.
So, can you tell me a way how to send authentication token to the server with headers?
But, if I use cookie then how to add headers to a request? How to send the request to the server?
The login response would include a Set-Cookie header. Then the browser will send a Cookie header on subsequent requests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.