Refused to apply style from ошибка

This is specific to TypeScript and Express.js

I Ctrl + F‘d «TypeScript» and «.ts» and found nothing in these answers, so I’ll add my solution here, since it was caused by (my inexperience with) TypeScript, and the solutions I’ve read don’t explicit solve this particular issue.

The problem was that TypeScript was compiling my app.ts file into a JavaScript file in my project’s dist directory, dist/app.js.

Here’s my directory structure. See if you can spot the problem:

.
├── app.ts
├── dist
│   ├── app.js
│   ├── app.js.map
│   └── js
│       ├── dbclient.js
│       ├── dbclient.js.map
│       ├── mutators.js
│       └── mutators.js.map
├── public
│   ├── css
│   │   └── styles.css
├── tsconfig.json
├── tslint.json
└── views
    ├── index.hbs
    └── results.hbs

My problem is that in app.ts, I was telling express to set my public directory as /public, which would be a valid path if Node.js actually were running TypeScript. But Node.js is running the compiled JavaScript, app.js, which is in the dist directory.

So having app.ts pretend it’s dist/app.js solved my problem. Thus, I fixed the problem in app.ts by changing

app.use(e.static(path.join(__dirname, "/public")));

to

app.use(e.static(path.join(__dirname, "../public")));

У меня была такая же проблема при использовании gulp

browserSync.init({
        server: {
            baseDir: 'src/'
        }
    });

проблема решилась изменением baseDir: ‘src/’ на baseDir: ‘dist/’

Если используете шаблон Бутстрап, то сделайте так:
link href=»bootstrap.min.css»
вместо так:
link rel=»stylesheet» href=»bootstrap.min.css»


Комментировать

Não tenho certeza se isso vai ajudar alguém, mas se você estiver usando o angular-cli, resolvi isso removendo a referência css do meu index.html e adicionando-a ao arquivo angular-cli.json na parte «estilo».
Depois de reiniciar meu servidor web, não tive mais esse problema.

Not sure if this will help anyone, but if you are using angular-cli, I fixed this by removing the css reference from my index.html and adding it to the angular-cli.json file under the «style» portion.
After restarting my webserver I no longer had that issue.

this works, thanks, for angular-cli this is the only viable and logical solution, as it is part of their process to add any stylesheet to angular.json, as well as bootstrap and other tools.

Last updated: Dec 03, 2020
— by: C. Smith

Over the past few years, the following error has become very common in the browser console:

Refused to apply style from ‘http://127.0.0.1:5500/styles/styles.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Plenty of developers face this problem regardless of the web technology used. So this is not a node.js, angular, express, webpack, spring, or whatever issue. Any surprising, but in 95% of cases, it’s a simple 404 Not Found error.

not_found

Quick check

You can also check for yourself if this is the problem. If you check on the network tab of the developer tool, you will probably see that the browser cannot load the stylesheet file. Or click on the link referenced in the error message, and most likely, you will see some kind of «not found» error in a new browser tab.

Solution

Check again carefully for typos in the link. Then again, seriously! In most cases, an omitted or forgotten letter s or .min extension is the culprit.

If you are sure that this is not a problem, then for some reason the web server you are using will not make the stylesheet file available on this path. And this is already going to be a configuration issue. That is already technology-dependent so accordingly, you need to continue to look for the reason why the file is not available. I can’t present these here because there are too many and I don’t even know them all.

The point is to change your search term and not look for the original error, but why the file is not available. 

Why is this the error message then?

The key is the X-Content-Type-Options response HTTP header. By default, some web servers send this header parameter with a value of nosniff . As a result, the browser blocks the stylesheet request if the MIME-type is not "text/css"

request_cancelled
That’s fine, but I specified a "text/css" type in the code, so what’s the problem? Because the requested file could not be found, the server returns a 404 error message, which is already "text/html" and is therefore not accepted as a valid stylesheet. See more details here.

Wrong solutions

There are also many bad solutions on the internet. Don’t use these:

  • Do not delete the rel attribute from the link element. The error will indeed disappear, but the browser will not apply that stylesheet.
  • Do not want to turn off MIME checking. Although the error message disappears from the console, the style sheet still does not load.
  • Do not replace the href attribute with src . The error message also disappears, but the browser still does not load the stylesheet. Besides, src is not a valid attribute for the link element.

I also had the same issue,

What I did was to rename the .htaccess on both the root directory and /pub directory. it fixed my problem.

Also, you can replace .htaccess with this

############################################
## uncomment the line below to enable developer mode

#   SetEnv MAGE_MODE developer

############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi

#    Action php5-cgi /cgi-bin/php5-cgi
#    AddHandler php5-cgi .php

############################################
## GoDaddy specific options

#   Options -MultiViews

## you might also need to add this line to php.ini
##     cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini

############################################
## this line is specific for 1and1 hosting

    #AddType x-mapp-php5 .php
    #AddHandler x-mapp-php5 .php

############################################
## default index file

    DirectoryIndex index.php

<IfModule mod_php5.c>

############################################
## adjust memory limit

    php_value memory_limit 768M
    php_value max_execution_time 18000

############################################
## disable automatic session start
## before autoload was initialized

    php_flag session.auto_start off

############################################
## enable resulting html compression

    #php_flag zlib.output_compression on

###########################################
## disable user agent verification to not break multiple image upload

    php_flag suhosin.session.cryptua off

</IfModule>

<IfModule mod_security.c>
###########################################
## disable POST processing to not break multiple image upload

    SecFilterEngine Off
    SecFilterScanPOST Off
</IfModule>

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    ###SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    #BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    #BrowserMatch ^Mozilla/4.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    #BrowserMatch bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    #SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    #Header append Vary User-Agent env=!dont-vary

</IfModule>

<IfModule mod_ssl.c>

############################################
## make HTTPS env vars available for CGI mode

    SSLOptions StdEnvVars

</IfModule>

<IfModule mod_rewrite.c>

############################################
## enable rewrites

    Options +FollowSymLinks
    RewriteEngine on

############################################
## you can put here your magento root folder
## path relative to web root

    #RewriteBase /magento/

############################################
## workaround for HTTP authorization
## in CGI environment

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

############################################
## TRACE and TRACK HTTP methods disabled to prevent XSS attacks

    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
    RewriteRule .* - [L,R=405]

############################################
## redirect for mobile user agents

    #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$
    #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
    #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

</IfModule>


############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead

    AddDefaultCharset Off
    #AddDefaultCharset UTF-8

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires

    ExpiresDefault "access plus 1 year"
    ExpiresByType text/html A0
    ExpiresByType text/plain A0

</IfModule>

###########################################
## Deny access to root files to hide sensitive application information
    RedirectMatch 404 /.git

    <Files composer.json>
        order allow,deny
        deny from all
    </Files>
    <Files composer.lock>
        order allow,deny
        deny from all
    </Files>
    <Files .gitignore>
        order allow,deny
        deny from all
    </Files>
    <Files .htaccess>
        order allow,deny
        deny from all
    </Files>
    <Files .htaccess.sample>
        order allow,deny
        deny from all
    </Files>
    <Files .php_cs>
        order allow,deny
        deny from all
    </Files>
    <Files .travis.yml>
        order allow,deny
        deny from all
    </Files>
    <Files CHANGELOG.md>
        order allow,deny
        deny from all
    </Files>
    <Files CONTRIBUTING.md>
        order allow,deny
        deny from all
    </Files>
    <Files CONTRIBUTOR_LICENSE_AGREEMENT.html>
        order allow,deny
        deny from all
    </Files>
    <Files COPYING.txt>
        order allow,deny
        deny from all
    </Files>
    <Files Gruntfile.js>
        order allow,deny
        deny from all
    </Files>
    <Files LICENSE.txt>
        order allow,deny
        deny from all
    </Files>
    <Files LICENSE_AFL.txt>
        order allow,deny
        deny from all
    </Files>
    <Files nginx.conf.sample>
        order allow,deny
        deny from all
    </Files>
    <Files package.json>
        order allow,deny
        deny from all
    </Files>
    <Files php.ini.sample>
        order allow,deny
        deny from all
    </Files>
    <Files README.md>
        order allow,deny
        deny from all
    </Files>

################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags

    #FileETag none

  • Главная
  • Вопросы

Всё проверила, но html не видит сss.

При просмотре кода в браузере пишет об ошибке: Refused to apply style from ‘http://127.0.0.1:5500/js/css/style.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Пробовала путь в css написать полностью, но тоже не работает.

На фото расположение и название папок

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wordpress интенсив</title>
    <link rel="stylesheet" href="cssstyle.css">
</head>
<body>
    <section class="promo">

    </section>
</body>
</html>

https://sun6-19.userapi.com/HTdE8rdLwEtF4NLzFKMtf7qA_pSObKiJ1sFySA/vjP89gfXHsk.jpg

Алёна Ольховская

3 years ago


  • Активные
  • Старые
  • Голоса

попробуйте указать так <link rel=»stylesheet» href=»css/style.css» type=»text/css»>

student_LmEygwQ4

3 years ago


Всё равно не работает

Алёна Ольховская

3 years ago


у вас index.html лежит в папке /js/, поэтому он пытается найти ваш css в папке /js/css/

перенесите index в корневую папку вашего проекта


«cssstyle.css»> у вас «слэш» с наклоном не в ту сторону, может поэтому? у меня тоже не подшиваются стили, почему не пойму :(

Елена Шугаева

3 years ago


4 ответов

Понравилась статья? Поделить с друзьями:
  • Remmina ошибка при запуске сеанса ssh kex error
  • Remlichtschakelaar controleren ошибка опель
  • Remlicht control ошибка опель
  • Remeza bk25 компрессор сброс ошибок
  • Remember me убрать ошибку меморайз