6

I'm trying to start a very simple server on my Mac so I can access a file from localhost.

I have node and express installed and this is all that it is in my server file.

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

app.use(express.static(__dirname, '/'));

app.listen(8080);

console.log("App listening on port 8080");

When I try to do:

node server

I get this as a response:

/Users/mt_slasher/node_modules/express/node_modules/serve-static/index.js:47
var opts = Object.create(options || null)
                ^
TypeError: Object prototype may only be an Object or null: /
    at Function.create (native)
    at Function.serveStatic (/Users/mt_slasher/node_modules/express/node_modules/serve-static/index.js:47:21)
    at Object.<anonymous> (/Users/mt_slasher/Desktop/My Projects/Basket/Site/server.js:4:23)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

I've run this same file on a Windows machine with the same files and had no problem.

After some digging, I found this line seems to be the main culprit:

app.use(express.static(__dirname, '/'));

Can someone tell me what might be happening?

3 Answers 3

11

That is because you are passing "/" as second parameter (options)

app.use(express.static(__dirname + '/'));

See serve-static:

function serveStatic(root, options) ...

https://github.com/expressjs/serve-static/blob/master/index.js

Also note that it would be better to use a different directory than your root e.g. express.static(__dirname + '/public') to avoid exposing your root.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thank you. I also moved my static files to a different directory. It's weird that my code worked on my Windows machine and not my Mac. I think there must be different versions of a package under the hood.
2

express.static is used to define directory where your "static" files reside look at here for more info.

It accepts only a string with the path you want to be static:

So your code should be:

app.use(express.static('/'));

Or

app.use(express.static(__dirname + '/'));

But that doesn't make much sense, imho.

Remove the line or define the real path where your assets files are.

2 Comments

I agree, that's why I wrote that doesn't make much sense.
Thanks for pointing me to that page. I'm a front-end coder so I have scant knowledge of back-end and node, so it was helpful to get a little more info.
0

The second parameter you are passing to express.static is incorrect. remove the second parameter. app.use(express.static(__dirname));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.