Chrome localhost未发送任何数据- ERR_EMPTY_RESPONSE

6l7fqoea  于 12个月前  发布在  Go
关注(0)|答案(4)|浏览(191)

使用VScode编写NodeJS
但是检查一下,localhost没有正确响应,它说“页面没有发送任何数据。我试着到处找,改变了所有可能的设置。
恢复Chrome设置清除缓存,清除历史记录,更改端口号,更改LAN设置。

''''

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}..`));

 ''''

想看网页上打印的所有课程。

sczxawaw

sczxawaw1#

我遇到了一个类似的问题,这是由使用http调用一个仅限https的API端点引起的。

kkih6yb8

kkih6yb82#

你的courses是一个对象。你需要把它作为字符串通过电线。将其作为json发送,浏览器将能够解析它。

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

要从浏览器获取输入,必须使用像body-parser这样的包,而不是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())
icomxhvb

icomxhvb3#

`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);`

你不需要添加app.use line in“body-parser”:“^1.19.0”这个版本,这是在我的时代运行的。

ev7lccsx

ev7lccsx4#

我遇到了同样的问题,令人惊讶的是,在cmd/powershell/windows终端中运行此命令以关闭WSL工作。

wsl --shutdown

相关问题