tocoolforscool
tocoolforscool

Reputation: 452

using files with express server

var express = require('express'),
    app = express(),
    db = require('./db'),
    bodyParser = require('body-parser'),
    controller = require('./controller');


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

app.get('/server', function (req, res) {
  console.log(__dirname);
    res.sendFile('/../client/index.html');
});

I have this express server set up but using the code above I get "Cannot GET /" when I view localhost:portnumber. If I change the GET method to:

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

I get "'C:\Users\TC\Documents\Desktop\myapp\multiplayerWebSite\server..\client\index.html' at Error (native)" and if I change it to:

app.get('/', function(req, res) {
  res.sendFile('../client/index.html');
});

I get "TypeError: path must be absolute or specify root to res.sendFile" Error: ENOENT: no such file or directory

The server was working perfectly when I had everything in the root directory, but I wanted to change the folder structure to make it more neat/professional. If anyone could tell me what I'm doing wrong I'd appreciate it greatly. Thank you in advance!

Upvotes: 1

Views: 71

Answers (1)

Gatsbill
Gatsbill

Reputation: 1790

You can use path module, there is a join method that take multiple paths to make one.

Exemple if you do:

path.join('test/musicfolder', '../videofolder/allreadyseen')

you will get 'test/videofolder/allreadyseen' .

you can see all the doc here : https://nodejs.org/api/path.html

var express = require('express'),
    path = require('path'),
    app = express(),
    db = require('./db'),
    bodyParser = require('body-parser'),
    controller = require('./controller');


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

app.get('/server', function (req, res) {
  console.log(__dirname);
    res.sendFile(path.join(__dirname, '../client/index.html'));
});

Upvotes: 2

Related Questions