Wednesday, 10 May 2017

How do I turn Node.js static images from a Document type to a image mime type

I am building a web application with Node.js. The basic app structure is set, but in order for me to do an API call to a specific API I need to have a static image.

I've already set up a static folder with app.use(express.static(path.join(__dirname, 'public')));

And if I try to view an image via the url i.e: localhost:3000/img/img.png, It displays: Resource interpreted as Document but transferred with MIME type image/png: "http://localhost:3000/img/img.png" in the console.

Does someone know how to serve all image with the correct mime type?

This is my entry file app.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var exphbs  = require('express-handlebars');
var ioServer = require('socket.io');
var request = require('request');
var imagecolors = require('imagecolors');

// These are the routers
var dashboard = require('./routes/dashboard');
var index = require('./routes/index');

var app = express();


// view engine setup
app.engine('handlebars', exphbs({
    defaultLayout: 'main',
    partialsDir: ['views/partials/']
}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'handlebars');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
// static folder
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', dashboard);
app.use('/image', index);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err,
        title: 'error'
    });
});

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + server.address().port);
});


via eltongonc

No comments:

Post a Comment