اذهب إلى المحتوى
  • 0

Express.static لا يعمل

محمد لارافيل

السؤال

لدي الكود التالي

var express = require('express');
var webpack = require('webpack');
var app = express();

//app.use(express.static(path.join(__dirname, "public")));
app.use("/", express.static(__dirname + "/public"));
//both not working. I have tried multiple ways....

app.get("/",function (req, res){
res.sendFile(__dirname + "/public/index/index.html")
});


app.listen(3000);

Webpack configs

module.exports = {
entry: './app/index/index.js',
output: {
    path: path.resolve(__dirname, 'public/index'),
    publicPath: '/public/index',
    filename: 'index_bundle.js'
},
module: {
    rules: [
        { test: /\.(js)$/, use: 'babel-loader' },
        { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
    ]
},
plugins: [
    new HtmlWebpackPlugin({
        template: 'app/index/index.html'
    })
]};

هيكلية الملفات

-public
        -index
          -index_bundle.js

يظهر لي الخطأ التالي عندما أحاول تحميل index_bundle.js:

GET http://localhost:3000/public/index/index_bundle.js 404 (Not Found)

كيف أحل المشكلة؟

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

 المشكلة في إعدادات Webpack. يجب أن تكون إعدادات الإخراج في Webpack تطابق المسار الذي يتم استخدامه في ملف الخادم (server) Express.

عندما تحاول الوصول إلى ملف "index_bundle.js" من ملف Express، يجب أن تكون الإعدادات الخاصة بمسار الإخراج في Webpack مطابقة للمسار الذي يتم استخدامه في الصفحة HTML. في هذه الحالة، يجب على Webpack إخراج الملف إلى المسار "public/index" ويجب أن يتم الوصول إليه عبر المسار "/public/index/index_bundle.js".

لحل المشكلة، يجب تغيير إعدادات الإخراج في Webpack كما يلي:

module.exports = {
entry: './app/index/index.js',
output: {
path: path.resolve(__dirname, 'public/index'),
publicPath: '/public/index/', // تغيير المسار إلى "/public/index/"
filename: 'index_bundle.js'
},
// ...
};

ومن ثم يجب استخدام هذا المسار في Express:

app.use("/public/index", express.static(__dirname + "/public/index")); // استخدام "/public/index" بدلاً من "/"

وبذلك يجب أن يكون بإمكانك الآن الوصول إلى "index_bundle.js" عبر المسار "http://localhost:3000/public/index/index_bundle.js".

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...