Node js cannot get ошибка

This is what i have, the filename «default.htm» actually exists and loads when doing a readFile with NodeJS.

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

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

app.listen(process.env.PORT);

The Error (in browser):

Cannot GET /

asked Nov 12, 2012 at 7:22

sia's user avatar

2

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content — to do so use:

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

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

Ilija's user avatar

Ilija

4,0754 gold badges32 silver badges46 bronze badges

answered Nov 12, 2012 at 7:31

Sdedelbrock's user avatar

SdedelbrockSdedelbrock

5,1421 gold badge18 silver badges13 bronze badges

2

I’ve noticed that I forgot the «slash» in the beginning of the Route as below
and I was getting same error :

Wrong :

app.get('api/courses',  (req, res) => { ... }
)

Correct :

  app.get('/api/courses',  (req, res) => { ... }
    )

answered Jun 6, 2019 at 21:15

Bulent Balci's user avatar

You need to define a root route.

app.get('/', function(req, res) {
  // do something here.
});

Oh and you cannot specify a file within the express.static. It needs to be a directory. The app.get('/'.... will be responsible to render that file accordingly. You can use express’ render method, but your going to have to add some configuration options that will tell express where your views are, traditionally within the app/views/ folder.

answered Nov 12, 2012 at 7:28

Daniel's user avatar

DanielDaniel

1,7022 gold badges13 silver badges19 bronze badges

I had the same problem, so here’s what I came up with. This is what my folder structure looked like when I ran node server.js

app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

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

should actually be

app.use(express.static(__dirname));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Overall, your code could look like:

var express = require('express');

var app = express();

app.use(express.static(__dirname));

app.listen(process.env.PORT);

answered May 21, 2016 at 19:52

CopyLeft's user avatar

CopyLeftCopyLeft

3112 silver badges6 bronze badges

I found myself on this page as I was also receiving the Cannot GET/ message. My circumstances differed as I was using express.static() to target a folder, as has been offered in previous answers, and not a file as the OP was.

What I discovered after some digging through Express’ docs is that express.static() defines its index file as index.html, whereas my file was named index.htm.

To tie this to the OP’s question, there are two options:

1: Use the code suggested in other answers

app.use(express.static(__dirname));

and then rename default.htm file to index.html

or

2: Add the index property when calling express.static() to direct it to the desired index file:

app.use(express.static(__dirname, { index: 'default.htm' }));

answered Sep 24, 2016 at 14:57

PTD's user avatar

PTDPTD

1,0281 gold badge16 silver badges23 bronze badges

1

Where is your get method for «/»?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

answered Nov 12, 2012 at 7:32

Serdar Dogruyol's user avatar

Serdar DogruyolSerdar Dogruyol

5,1373 gold badges23 silver badges32 bronze badges

You need to add a return to the index.html file.

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

app.get('*', function(req, res) {res.sendFile(path.join(__dirname + '/build/index.html')); });

answered Nov 10, 2020 at 11:30

xplorer1's user avatar

xplorer1xplorer1

1,2341 gold badge10 silver badges13 bronze badges

Provide full path for example I am running my app on https://ugoods.in/nodeapp

app.get('/nodeapp', (req, res) => {
  res.send('Hello World!')
})

If you will run directly on http://ugoods.in or http://localhost

app.get('/', (req, res) => {
  res.send('Hello World!')
})

answered Jul 7, 2021 at 6:08

Md Rehan's user avatar

Md RehanMd Rehan

3091 silver badge8 bronze badges

1

I had the same issue. Solved it by small changes like below.

var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));

Got help from here (ExpressJS Documentation — Serving static files).

answered Mar 15, 2017 at 14:49

Amal Augustine Jose's user avatar

In my case, the static content was already being served:

app.use('/*', express.static(path.join(__dirname, '../pub/index.html')));

…and everything in the app seemed to rely on that in some way. (path dep is require('path'))

So, a) yes, it can be a file; and b) you can make a redirect!

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

Now anyone hitting / gets /index.html which is served statically from ../pub/index.html.

Hope this helps someone else.

answered Mar 6, 2018 at 2:46

Chaim Eliyah's user avatar

Chaim EliyahChaim Eliyah

2,7334 gold badges23 silver badges37 bronze badges

I was facing the same problem as mentioned in the question. The following steps solved my problem.

I upgraded the nodejs package link with following steps

  1. Clear NPM’s cache:

    npm cache clean -f
    
  2. Install a little helper called ‘n’

    npm install -g n  
    

Then I went to node.js website, downloaded the latest node js package, installed it, and my problem was solved.

user812786's user avatar

user812786

4,2624 gold badges37 silver badges50 bronze badges

answered Jan 22, 2016 at 14:01

Akshay Vijay Jain's user avatar

1

var path = require('path');

Change app.use(express.static(__dirname + '/default.htm')); to
app.use(express.static(path.join(__dirname + '/default.htm')));.

Also, make sure you point it to the right path of you default.html.

JJJ's user avatar

JJJ

32.8k20 gold badges89 silver badges102 bronze badges

answered Sep 26, 2017 at 11:00

Officialzessu's user avatar

0

You need to restart the process if app.get not working. Press ctl+c and then restart node app.

answered Mar 1, 2019 at 10:22

Ashwani Panwar's user avatar

Ashwani PanwarAshwani Panwar

3,5313 gold badges42 silver badges65 bronze badges

«Cannot » happens when a request is sent to non-defined target.
For example:

app.get('/',()=>{});

This would handle requests sent to localhost/ but not localhost/path.

Please, make soure there is a routing defined for the URL you are trying to access.
Actual response you might get:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /path</pre>
</body>
</html>

answered Mar 11, 2022 at 7:09

Maciej Wakula's user avatar

I was also getting the same error as «Cannot GET /» in my MERN application in the network tab. I added these lines of code in my index.js(in backend) file after referring to this article https://coursework.vschool.io/deploying-mern-app-to-heroku/ :

Right before my app.listen():

app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});

and also changed a line in

if(process.env.NODE_ENV === 'production')

from this:

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

to this:

app.use(express.static(path.join(__dirname, "client", "build")))

So, check this too, if making these changes work for you.

answered Mar 26, 2022 at 11:31

Suryakant's user avatar

I had this exact issue, my error source might differ to what your source of error was though.

However, as for me, it was because I was running the app instance on CPanel inside subfolder as:

app.get("/", (request, response) => {
       response.status(200).send("Hello there");
})

Results:

Can not GET /

So, I realized I was setting wrong parameter, and what I did was:

app.get("/foldername/", (request, response) => {
       response.status(200).send("Hello there, it works!");
 })

Results:

Hello there, it works!

answered May 11, 2021 at 13:27

Amin Matola's user avatar

Amin MatolaAmin Matola

1372 silver badges7 bronze badges

Another solution is to check whether your .static() parameter refers to the correct folder of your other website files (.html, .css, ..).
this folder should be in the same directory of the server.js file.
don’t know why though, I tried to put it in a different directory and pass ./website for example but it didn’t work. :/

answered Apr 18, 2021 at 16:20

Muhammad Ihab's user avatar

2

Instead of using «app.use», try to use «app.get». It works on my machine.

answered May 3, 2022 at 2:59

PARAMJEET SINGH's user avatar

1

Problem Statement: On running a Node.js application URL on the web browser it throws the following error: 

Cannot GET/ 

Example: Let’s create a simple Node.js application that throws the same error.

Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express

To install Express as dependencies inside your project

Step 3: Create Server File: Create an ‘app.js’ file, inside this file require an express Module, and create a constant ‘app’ for creating an instance of the express module.

const express = require('express')
const app = express()

Step 4: Create a Message Route: Create a get route using app.get() method which sends “hello” as a text to the web browser.

app.get("/messages", (req, res) => {
   res.send("Hello");
});

Step 5: Set up a port to run our server: We will do it by using the express, app.listen() method.

app.listen(3000, () => {
  console.log("listening on http://localhost:3000");
})

Complete Code:

Javascript

const express = require('express')

const app = express()

app.get("/messages", (req, res) => {

    res.send("Hello");

});

app.listen(3000, () => {

})

Output:

Reason: Since in the server file, we create a get route for ‘/messages’ URL but inside the browser, we try to get the ‘/’ URL which is not specified in our server file that’s why it throws the error.

Solution Approach: We have to set up a universal route, and when any route or URL which are not specified inside the server file will call then the universal URL sends a “404 URL NOT FOUND” message.

app.get("/:universalURL", (req, res) => {
   res.send("404 URL NOT FOUND");
});

Complete Code:

Javascript

const express = require('express')

const app = express()

app.get("/messages", (req, res) => {

    res.send("Hello");

});

app.get("/:universalURL", (req, res) => {

    res.send("404 URL NOT FOUND");

});

app.listen(3000, () => {

})

Output:

Last Updated :
04 Aug, 2022

Like Article

Save Article

closeup photo of yellow Labrador retriever puppy

Reason: Since in the server file, we create a get route for ‘/messages’ URL but inside the browser, we try to get the ‘/’ URL which is not specified in our server file that’s why it throws the error.

Solution Approach: We have to set up a universal route, and when any route or URL which are not specified inside the server file will call then the universal URL sends a “404 URL NOT FOUND” message.

app.get("/:universalURL", (req, res) => {
   res.send("404 URL NOT FOUND");
});

Complete Code:

Javascript

const express = require('express')

const app = express()

app.get("/messages", (req, res) => {

    res.send("Hello");

});

app.get("/:universalURL", (req, res) => {

    res.send("404 URL NOT FOUND");

});

app.listen(3000, () => {

})

Output:

Last Updated :
04 Aug, 2022

Like Article

Save Article

To fix the ‘Error: Cannot GET /’ error message with Node.js and Express, we need to add the route handler for the GET / route.

For instance, we write

app.get("/", (req, res) => {
  res.render("index.html");
});

to call app.get with '/' and the route handler to handle GET requests to the / route.

In the route handler for the GET / route, we call res.render to render the index.html template on the screen.

Related Posts

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

View Archive

The freeCodeCamp Forum

Loading

Introduction

This article has a specific content on solving an error message. The detail of the error message exist in the title of this article. It is an error message of ‘Cannot Get /’ exist in the page of NodeJS application. Actually, the error appear upon executing a NodeJS application. Running the application by executing a command in the command line interface as follows :

[admin@10 nodejs]$ node app.js
Test NodeJS !

But upon accessing the page via web browser, the following is the image of the page after successfully executing the NodeJS application :

How to Solve Error Message Cannot Get / in NodeJS Application

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

View Archive

The freeCodeCamp Forum

Loading

Introduction

This article has a specific content on solving an error message. The detail of the error message exist in the title of this article. It is an error message of ‘Cannot Get /’ exist in the page of NodeJS application. Actually, the error appear upon executing a NodeJS application. Running the application by executing a command in the command line interface as follows :

[admin@10 nodejs]$ node app.js
Test NodeJS !

But upon accessing the page via web browser, the following is the image of the page after successfully executing the NodeJS application :

How to Solve Error Message Cannot Get / in NodeJS Application

How to Solve Error Message Cannot Get / in NodeJS Application

Actually, the code has a part for listening to a specific port. In the context of this article, the application is listening to port 3001. The following is the actual content of the source code with the file name of ‘app.js’ :

const express = require("express");
const app = express();

app.get("/");
app.listen(3001);

console.debug("Test NodeJS !");

So, while printing the ‘Test NodeJS !’ in the command line interface, it also listens for incoming request in port 3001. But apparently, accessing port 3001 via web browser fail with the error message as in the above image.

Solving the problem

In order to solve the problem, just fix the above line of code especially in the following line :

app.get("/");

Upon executing a GET request by typing the address of ‘localhost:3001’ in the web browser’s address bar, the above image appear. The error message is ‘Cannot Get /’. It is because there is no definition for responding the value from the line of ‘app.get(‘/’)’. In order to a page retrieving a responding value, just define it in the line of the code. The following is one of the method for defining at responding value to the GET request as follows :

app.get("/",(req,res) => res.send("Response from the GET request"));

Another form of definition with the full-length syntax of the function exist as follows :

app.get("/", function (req,res) {
res.send("Response from the GET request")
});

So, the full content of the file with the name of ‘app.js’ exist as follows :

const express = require("express");
const app = express();
app.get("/",(req,res) => res.send("Response from the GET request"));
app.listen(3001);

console.debug("Test NodeJS !");

Or another form of the function definition displaying the full content of the file :

const express = require("express");
const app = express();
app.get("/", function (req,res) {
res.send("Response from the GET request")
});app.listen(3001);

console.debug("Test NodeJS !");

Понравилась статья? Поделить с друзьями:
  • Nod32 ошибка при подключении к серверу
  • No module named config ошибка
  • Nod32 ошибка обновления 0x1106 nod32
  • No module named colorama ошибка
  • No mans sky ошибка приложения