Issues with connecting static files in express.js

Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page.

The code in my index.js file looks like this:

app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, 'public'), { "extensions": ["html", "css", "js"] }));

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/login.html'));
});

app.post('/login', (req, res) => {
    console.log(req.body.username);
    res.redirect('/chat');
});

app.get('/chat', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/chat.html'));
});

Here's a snippet from my login.html file:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/login.css">
    <title>Log in</title>
</head>

<body>
    
    <div class="wrapper">
        <form action="/login" method="post" class="form">
            <h1>Enter to the chat</h1>
            <div class="username-container">
                <label for="username">Your name:</label>
                <input type="text" name="username" id="username" maxlength="10" required>
            </div>
            <button type="submit" id="submit">Submit</button>
        </form>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="./js/login.js"></script>
</body>

Based on the project structure below:

  ./public
    ./css
      ./login.css
      ./styles.css
    ./js
      ./login.js
      ./main.js
    ./chat.html
    ./login.html
  ./index.js

I've also added some code from login.js regarding form submission:

form.addEventListener('submit', event => {
       event.preventDefault();

       console.log('Form submitted');

       socket.emit('login', {
           username: username.value.trim()
       });
});

I see the message "Form submitted" in the console, but the redirect is not happening. Interestingly, it was working fine before I connected styles to the server and encountered MIME TYPE errors. There are no errors showing up in the console currently.

Answer №1

Give this code a try in index.js and observe if it makes a difference.

app.use(express.static(path.join(__dirname, 'public'), { "extensions": ["html", "css", "js"] }));

Answer №2

Your code snippet is preventing the form from being submitted using event.preventDefault().

form.addEventListener('submit', event => {
       event.preventDefault();

       console.log('Form submitted');

       socket.emit('login', {
           username: username.value.trim()
       });
});

By blocking the default submission, no POST request is sent to the server, resulting in no redirect. It's not clear why you are preventing the default behavior. If you want the form to submit as usual, simply remove event.preventDefault():

form.addEventListener('submit', event => {
       console.log('Form submitted');
       socket.emit('login', { username: username.value.trim() });
});

Keep in mind that sending a message through socket.io upon form submission may not be very useful because when the form is submitted, it will trigger a page reload, closing the existing socket connection and creating a new one if needed. This means the message sent on the previous connection may never reach its destination.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

Preventing the sidebar from overlapping with the main content in Bootstrap layout

My layout is set up as follows: Example I am encountering an issue when resizing the window, as there is overlap with the main content. Here is an example of the issue How can I prevent this overlap while still maintaining padding? Below is my HTML an ...

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

Mongoose: implement the schema from another model

I have a model 'Template' which I need to maintain its history in another model called 'TemplateHistory'. Instead of redefining the schema, how can I utilize the existing Template Schema for the HistorySchema? var Schema = new mongoose ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Error in Node.js: Unable to assign headers once they have already been sent to the client

I'm encountering the issue of receiving the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" error in my code. router.get("/", verify, async (req, res) => { const user = await pool.query("SELECT * FROM users W ...

Viewing the JSON Data

Support: $scope.createTimeSlots = function(interval, field) { var startingTime = moment().hours(8).minutes(0); field.timeslots = []; for (var i = 0; i < interval; i++) { $scope.intervals = 60; field.timeslots.push(startingTi ...

The functionality of JQuery ceases to function properly once the BxSlider plugin is activated

I've encountered a strange issue while using the BxSlider plugin of jQuery on my page. When I implement the code for the slider with BxSlider, all other custom functions seem to stop working without any errors being displayed in the console. I've ...

AngularJS: when only one line is visible, the other remains hidden

Issue with AngularJS: Only One Line Displaying Instead of Both I am encountering an issue with my AngularJS code where only one of the elements is displaying on my page. function Today($scope, $timeout) { $scope.now_time = 0; (function update() { ...

Tips for successfully sending an array of arrays with jQuery ajax

I have an array in PHP that looks like this: $treearr = array( array("root","search","Search",false,"xpLens.gif"), array("root","hometab","Home Tab",false,"home.gif"), array("root","stafftab","Staff Tab",false,"person.gif"), array ("stafftab","new ...

Incorporate a Flask variable into a webpage seamlessly without refreshing the page

I am facing a challenge in importing the variable test_data from Flask to my webpage without having to reload it. I have tried clicking a button, but haven't been successful so far. Any suggestions? Flask: @blueprint.route('/data_analysis' ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

What is the name of the file that contains a class?

I am curious about identifying the file that called a specific class: database.ts class Database { constructor() { console.log(`I want to know who called this class`); } } server.ts import Database from 'database.ts'; new Databa ...

Arranging buttons in a row with Bootstrap 5

Struggling to align the buttons on my webpage side by side in the center, I've tried two Bootstrap 5 classes but they're not achieving the desired look: https://gyazo.com/c23f2eade4614380aec547b11e61387a https://gyazo.com/e40a678b02c9f641f746b1c ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Adjusting the header and unordered list on resize

I need help with my portfolio website. I can't seem to figure out how to make my header and navigation menu stack on top of each other when the page is small, and then go back to their normal layout when the page is larger. Below is the HTML code I&a ...

Encountering an issue when using both the Google Maps API and Google URL Shortener API within the same program

Recently, I developed a program that involves passing data to an iframe through a URL. However, due to the limitation of Internet Explorer supporting only 2083 characters in a URL, I decided to use the Google URL Shorten API to shorten the URL before sendi ...

Issue encountered in transmitting information from JSP to servlet

I am facing an issue with receiving data from JSP to servlet. I understand that I need to serialize this data using JSON. In my JSP, I have written the following JavaScript code: var myJSONText = JSON.stringify(items); document.getElementById('test&a ...