Click here to Skip to main content
15,789,700 members
Please Sign up or sign in to vote.
1.11/5 (2 votes)
I keep getting this error on console.:

"Refused to execute script from 'http://localhost:3000/js/main.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."

I tried every way I could find on the internet and none of them worked. I shared my codes on code snippet. I want my sign up form to direct me to home page but it doesnt direct me anywhere. It just giving me error on console. I shared my index.js adminRoutes.js and indexRoutes.js codes with you. I used mongodb nodejs and express.js on this project. I just want to click sign up and I want it to direct me to home page which is defined as /

I can add more codes if its necessary.

indexRoutes.js:

<pre>const express = require('express'),
router = express.Router();



//ARRAY

let data= [
    {
        postTitle: "Blog Denemesi",
        postSubtitle: "Bu ilk blog denemesi ve video çok sıkıcı.",
        image: "https://images.unsplash.com/photo-1564177611049-76e2933c6017?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80"

    },

    {
        postTitle: "Testing a blog",
        postSubtitle: "This is a blog testing",
        image: "https://images.unsplash.com/photo-1552664730-d307ca884978?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80"

    },

    {
        postTitle: "Test Test",
        postSubtitle: "Lets see whats gonna happen",
        image: "https://images.unsplash.com/photo-1562762394-3acfba62a48e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80"

    },




]


//ARRAY Bitiş

router.get("/", (req, res)=>{
    res.render('home' , {data : data});
 }) ;

 router.get("/about", (req,res)=>{
    res.render('about');
 }) ;

 router.get("/contact", (req,res)=>{
    res.render('contact');
 }) ;



module.exports = router;


adminRoutes.js:

<pre>const express = require('express'),
passport = require("passport"),
User= require('../models/userModel'),
router = express.Router();


//ARRAY

let adminActions =[

    {
        actionId:1,
        actionName: "changeHomeImage",
        displayName: "Change Home Image"

    },
    {
        actionId:2,
        actionName: "changeAboutImage",
        displayName: "Change About Image"

    },
    {
        actionId:3,
        actionName: "changeAboutText",
        displayName: "Change About Text"

    },
    {
        actionId:4,
        actionName: "addNewBlog",
        displayName: "Add New Blog"

    },
    {
        actionId:5,
        actionName: "listAllBlogs",
        displayName: "List All Blogs"

    }
];

//ARRAY Bitiş

router.get("/admin", (req, res)=>{
    res.render("admin/admin",{adminActions:adminActions});
 }) ;

 router.get("/signin", (req,res)=>{
    res.render("admin/signin");
 }) ;

 router.post("/signin", (req,res)=>{
 }) ;

 router.get("/signup", (req,res)=>{
    res.render('admin/signup');
 }) ;

 router.post("/signup", (req,res)=>{
   
    let newUser = new User({username:req.body.username});
    User.register(newUser, req.body.password, (err, user)=>{
        if (err){
            console.log(err);
            res.redirect("/signup");
        }
        passport.authenticate("local")(req, res, ()=>{
            res.redirect("/");

        });
    })
}) ;

module.exports = router;


index.js

<pre>const mongoose = require("mongoose"),
    express= require ("express"),
    passport = require("passport"),
    LocalStrategy = require("passport-local"),
    User= require("./models/userModel"),
    expressSession = require("express-session"),
    bodyParser = require("body-parser"),

    app = express();

const { Passport } = require("passport");
    //Routes

    const indexRoutes = require("./routes/indexRoutes");
          adminRoutes = require("./routes/adminRoutes");



    //App Config

mongoose.connect("mongodb://localhost/BlogApp");
app.set('view engine' , 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));

//Passport Config

app.use(require("express-session")({
     secret: "bu güvenlik cümlesi",
     resave: false,
     saveUninitialized: false

}));

app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());


//Routes Using

app.use(indexRoutes);
app.use(adminRoutes);

//Server 

const server = app.listen(3000, (err)=> {
    if(err){
      console.log(err);
    }

      console.log('App Started. Port number  : %d ', server.address().port);

})



signup.js

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Clean Blog - Start Bootstrap Theme</title>
        <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
        <!-- Font Awesome icons (free version)-->
        <script src="https://use.fontawesome.com/releases/v6.3.0/js/all.js" crossorigin="anonymous"></script>
        <!-- Google fonts-->

        <!-- Core theme CSS (includes Bootstrap)-->
        <link href="css/main.css" rel="stylesheet" />
        <!--OLDU MU EMİN DEĞİLİM-->

        <!--Bootstrap Link-->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

        <!--Bootstrap FONTAWESOME-->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.1/css/fontawesome.min.css" integrity="sha384-QYIZto+st3yW+o8+5OHfT6S482Zsvz2WfOzpFSXMF9zqeLcFV0/wlZpMtyFcZALm" crossorigin="anonymous">

        <!--JQuery CDN-->
        <script
           src="https://code.jquery.com/jquery-3.6.4.js"
           integrity="sha256-a9jBBRygX1Bh5lt8GZjXDzyOB+bWve9EiO7tROUtj/E="
           crossorigin="anonymous"></script>

           <style>
            #mainNav .navbar-brand{
                color: black;
            }
            #mainNav .navbar-brand:hover{
                color: coral;




            }
            #mainNav .navbar-nav > li.nav-item > a{
                color: black;
                background-color: black;
                
                
            }
            #mainNav .navbar-nav > li.nav-item > a:hover{
                color: coral;

            }
           </style>

    </head>
    <body>
        <!-- Navigation-->
        <nav class="navbar navbar-expand-lg navbar-light" id="mainNav">
            <div class="container px-4 px-lg-5">
                <a class="navbar-brand" href="/">Start Bootstrap</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
                    Menu
                    class="fas fa-bars">
                </button>
                <div class="collapse navbar-collapse" id="navbarResponsive">
                    <ul class="navbar-nav ms-auto py-4 py-lg-0">
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/">Home</a></li>
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/about">About</a></li>
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/contact">Contact</a></li>
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/signin">Sign In</a></li>
                    </ul>
                </div>
            </div>
        </nav>

<div class="container" style="margin-top: 5%;">
    <h1 style="text-align: center;">Sign Up Form</h1>
    <h3 style="text-align: center; color: red;">ADMIN</h3>
<form>
    <div class="form-group">
      <label for="exampleInputEmail1">Email address</label>
      <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
      <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Password</label>
      <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
    </div>
    <div class="form-check">
      <input type="checkbox" class="form-check-input" id="exampleCheck1">
      <label class="form-check-label" for="exampleCheck1">Check me out</label>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

</div>

<%- include ('../partials/footer') %>


main.js

/*!
* Start Bootstrap - Clean Blog v6.0.9 (https://startbootstrap.com/theme/clean-blog)
* Copyright 2013-2023 Start Bootstrap
* Licensed under MIT (https://github.com/StartBootstrap/startbootstrap-clean-blog/blob/master/LICENSE)
*/
window.addEventListener('DOMContentLoaded', () => {
    let scrollPos = 0;
    const mainNav = document.getElementById('mainNav');
    const headerHeight = mainNav.clientHeight;
    window.addEventListener('scroll', function() {
        const currentTop = document.body.getBoundingClientRect().top * -1;
        if ( currentTop < scrollPos) {
            // Scrolling Up
            if (currentTop > 0 && mainNav.classList.contains('is-fixed')) {
                mainNav.classList.add('is-visible');
            } else {
                console.log(123);
                mainNav.classList.remove('is-visible', 'is-fixed');
            }
        } else {
            // Scrolling Down
            mainNav.classList.remove(['is-visible']);
            if (currentTop > headerHeight && !mainNav.classList.contains('is-fixed')) {
                mainNav.classList.add('is-fixed');
            }
        }
        scrollPos = currentTop;
    });
})


Footer.ejs

        <!-- Footer-->
        <footer class="border-top">
            <div class="container px-4 px-lg-5">
                <div class="row gx-4 gx-lg-5 justify-content-center">
                    <div class="col-md-10 col-lg-8 col-xl-7">
                        <ul class="list-inline text-center">
                            <li class="list-inline-item">
                                <a href="#!">
                                    
                                        class="fas fa-circle fa-stack-2x" href="#!">
                                        ^__i class="fab fa-facebook-f fa-stack-1x fa-inverse">
                                    
                                </a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#!">
                                    
                                        ^__i class="fas fa-circle fa-stack-2x">
                                        ^__i class="fab fa-github fa-stack-1x fa-inverse">
                                    
                                </a>
                            </li>
                        </ul>
                        <div class="small text-center text-muted fst-italic">Copyright © Your Website 2023</div>
                    </div>
                </div>
            </div>
        </footer>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
      <script src="js/main.js" type="text/javascript"></script>
    </body>
</html>


What I have tried:

I tried eveything I could find on the Internet. I asked it even on StackOverFlow I also think it may be because I dont have content type header I also doont know how to add content type header to javascript. Any help appreciated.
Posted
Updated 28-Mar-23 14:13pm
v2
Comments
Chris Copeland 28-Mar-23 6:57am    
I may be being blind but I can't see anywhere in the code you've provided that references a main.js file? Is this file being loaded server-side or is it being loaded by the browser? Ideally we could do with being able to see the part of the code that loads it. The error though clearly indicates that for some reason the JS file is being returned with a mime-type of text/html which isn't compatible with the type of a JS file.

You showed everything except the one line that loads the "main.js" script and that's the one that matters.

Judging by the error message alone, you need to change that <script> tag to read something like:
<script src="...\main.js" type="text/javascript"></script>
 
Share this answer
 
I solved the problem writing down how to do it in case someone will face with same error.

1)Move js folder in public folder 2)Write the code belove in signup.ejs:
<script>
document.getElementById("adminSignup").onsubmit = (e) => {
   console.log("dsadsa");
   e.preventDefault();
   window.location.href = "/";
};
/pre>
3)Give form an ID:
<pre>
<form id="adminSignup">

4)Add in index.js
app.use(express.static('js'));

Thats all! Now your code is ready to work!
 
Share this answer
 
Comments
Dave Kreskowiak 29-Mar-23 0:41am    
You didn't really fix the problem correctly. You only worked around it without understanding it.

"Move js folder in public folder"? Whatever that means...

"Writing the code belove in signup.ejs"? All you did was move the code you needed from one file, which you're not loading correctly, to another file that is loading correctly.

Like I said, you're not understanding the problem to call this a solution.
Busenur Çetin 29-Mar-23 1:11am    
bro whats wrong with you? why are you so rude? if you have any suggestion you can just write it down. I was trying to solve this problem for days and spent hours but you are acting like you were the one who spent effort on it. I'd like to see your solution too. If you got one.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900