user7665661
user7665661

Reputation:

localhost didn't send any data - ERR_EMPTY_RESPONSE

Using VScode to write NodeJS

But to check, localhost isn't responding properly, it says "the page didn't send any data. I tried looking everywhere and changed all the possible settings I can.

restored chrome settings cleared cache, cleared history, changed port numbers, changed LAN settings.

 ''''

const Joi = require('joi');
const express = require('express');
const app = express();

app.use(express.json); //to take inputs ffrom the browser
const courses = [
{id: 1, name: "course 1"},
{id: 2, name: "course 2"},
{id: 3, name: "course 3"},
 ];

app.get('/', (req, res) =>{
res.send("Hello world!!");
res.end();
});

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

const port = process.env.port || 8080;
app.listen(port, ()=> console.log(`Listining on port ${port}..`));

 ''''

Want to see all the courses printed on the webpage.

Upvotes: 9

Views: 91322

Answers (4)

Philipos D.
Philipos D.

Reputation: 2310

I had the same problem and surprisingly running this command in cmd/powershell/windows terminal to turn off WSL worked.

wsl --shutdown

Upvotes: 0

Thabiso Mofokeng
Thabiso Mofokeng

Reputation: 729

I had a similar problem which was caused by calling an https only api endpoint using http.

Upvotes: 11

rudr'a rajput
rudr'a rajput

Reputation: 21

`package.json
"dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^3.0.1",
    "express": "^4.17.1",
    "mongoclient": "^1.0.3",
    "mongodb": "^2.2.33",
    "mongoose": "^5.8.12"
  }

app.js

const express = require('express');
const bodyParser=require('body-parser');
const app=express();

var db=require('./db')
var user=require('./module/user');

const port=process.env.PORT || 8080;
//to read the name property from html or ejs form or page body parser used there for.(tunnel)
app.use(bodyParser.urlencoded({ extended: true}))
//app.use(bodyParser.json);`

you don't need to add app.use line in "body-parser": "^1.19.0" this version, this is run in my era.

Upvotes: 0

1565986223
1565986223

Reputation: 6718

Your courses is an object. You need to send it as string over wire. Send it as json and the browser will be able to parse it.

app.get('/api/courses/', (req, res) => {
  // change here, your object is stringified to json by express
  res.json(courses);
});

To take input from browser, you'd have to use packages like body-parser and not app.use(express.json)

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Upvotes: 1

Related Questions