2

Установил nodejs, expressjs. Не получается подключить локальный bootstrap к html файлу. Не работает именно при localhost:3000. Если запустить отдельный index.html, то все локальные пути работают.

    <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" type="text/css">  


    <title>Hello, world!</title>
  </head>
  <body>
      <div class="container">
            <h1>Hello, world!</h1>    
      </div>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="node_modules/jquery/dist/jquery.slim.min.js" type="text/javascript"></script>></script>
    <script src="node_modules/popper.js/dist/popper.min.js" type="text/javascript"></script>></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.min.js" type="text/javascript"></script>></script>
  </body>
</html>

package.json:

    {
  "name": "bootstrap-protipe",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bootstrap": "^4.2.1",
    "express": "^4.16.4",
    "font-awesome": "^4.7.0",
    "fs": "0.0.1-security",
    "jquery": "^3.0.0",
    "popper.js": "^1.14.6"
  }
}

Сервер запускается app.js

        var express = require('express');
    var app = express();
    app.get('/', function (req, res) {
                res.sendFile( __dirname + '/index.html');
        })

    app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
    });
6
  • а какой-нибудь другой локальный css получается подключить? П.С. - никогда ничего не ложите в папку node_modules
    – Dmytro
    21 янв 2019 в 9:08
  • Так модули по умолчанию устанавливаются в node_modules. Собственно npm i --save bootstrap.
    – ncux199rus
    21 янв 2019 в 9:19
  • лучше бы Вы на вопрос ответили, который Вам задали
    – Dmytro
    21 янв 2019 в 10:04
  • Прошу прощения. Другой файл подключить также не получается. в консоле выдает ошибку - Refused to apply style from 'localhost:3000/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
    – ncux199rus
    21 янв 2019 в 11:55
  • 3
    Чтобы раздавать файлы с локального сервера, не мешало бы использовать express.static('public'). public - это название директории на твоём сервере, в которой ты хотел бы положить некоторые статические файлы для раздачи. Т.е. в том месте, где лежит твой index.js ты создаёшь папку public, кидаешь в неё bootstrap.min.js. После этого добавляешь в index.js такую строку: app.use(express.static('public')) и всё. Далее ты можешь в index.html прописать в атрибуте src тега script src="bootstrap.min.js" и файл с bootstrap должен подтянуться 21 янв 2019 в 13:03

2 ответа 2

2

Создал в главной директории каталог public. Перенес в него index.html, и все файлы получилось примерно следующее.

index.html

    <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="bootstrap.min.css">        
  </head>
  <body>
      <script src="vue.js"></script>

app.js

var express = require('express');
    var app = express();        
    app.use(express.static('public'))
    app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
    });
0

index.html:

<link rel="stylesheet" href="css/bootstrap.min.css">

app.js:

app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'))
1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.