后端代码向客户端发送响应,但在控制台日志中不显示其他行输出



我正在为我的应用程序运行在Node.js上编写的后端代码。当我将后端托管在端口上时,我能够获得对客户端的API响应,但是没有显示应该显示在控制台日志(在Node中)中的输出。我假设当我在本地主机端口上运行此代码时,应该执行整个代码,从而导致控制台日志输出(例如:"DB connected"应该显示在控制台日志中)。但这并没有发生。只显示post请求控制台日志O/P。(回复已发送)。为什么会发生这种情况?

注意:post请求O/P只在我post到后端时显示。默认情况下,它不被显示,这是预期的行为。

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import DB from "./env";
const app = express();
// DB connection
mongoose.connect(DB,{})
.then(() => {console.log("DB connected")})
.catch((error) => {error});
//middlewares
app.use(express.json({}));
app.use(cors({
origin:["http://localhost:3000"],
}));
//the actual backend response from server
app.post("/" , (req,res) => {
console.log("response sent");
//console.log(req.body.email);
//console.log(req.body);
res.end("backnd working");
})
//listen on port 8000
app.listen(8000);

评论中解释的大部分内容,请先阅读。

// load environmental variables.
require("dotenv").config();
// require modules.
const express = require("express"),
mongoose = require("mongoose"),
cors = require("cors"),
// app contains all express stuff.
const app = express();
// showing ports of your app is dangerous.
// get port and host from .env file by using dotenv package.
const PORT = process.env.PORT || 3000,
HOST = process.env.HOST || "localhost";
// you should use a seperate file to connect to database.
// here is the implementation of db.js file.
// anonymous function it will run automatically
(async () => {
// try and catch block to handle error
try{
await mongoose.connect(process.env.DB, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log("Connection SuccessFull");
}catch(err){
console.log(`no connection due to: ${err}`);
};
})();
// middlewares
app.use(express.json());
app.use(cors({
origin:["http://localhost:3000"],
}));
// try to use express router in a seperate file for better consistency
// The home page api
app.post("/" , (req, res) => {
console.log(`The home api hitted!
Main data is ${req.body}`);
res.status(200).send("backend working");
})
// listen app on given port and host
app.listen(PORT, HOST, (err) => {
// if error occured then this will fire else log success message to console.
if(err) console.log(err);
console.log(`The app started successfully on http://${HOST}:${PORT}/`);
});

如果有什么问题,请告诉我,我会解决的。

我不能100%肯定这将工作!

谢谢!

最新更新