Cannot set headers after they are sent to the client Express - javascript

I am getting error " Cannot set headers after they are sent to the client".Please help me.When I try the same thing on postman it works fine.
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/",function(req,res){
const apiKey="ae148f2088da42d7a47ac8e44a4a2768";
const url="https://newsapi.org/v2/top-headlines?country=in&category=business&apiKey="+apiKey;
https.get(url,function(response){
response.on("data",function(data){
const news=JSON.parse(JSON.stringify(data));
res.send("news data"+news);
})
})
})
app.listen(3000, function() {
console.log("Server started on port 3000");
});

The data event fires whenever you get some data from the HTTP stream. It will fire multiple times until all the data has arrived.
Consequently, with your current code, you are calling send multiple times for each request.
You need to store that data somewhere (e.g. concatenating it in a variable) and then only do something with it when the end event fires.
A better approach might be to stop using the built-in https module and use something with a more modern design (such as Axios).

This is the answer for the question.The problem is solved
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const axios=require("axios");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/",async function(req,res){
const apiKey="ae148f2088da42d7a47ac8e44a4a2768";
const url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=ae148f2088da42d7a47ac8e44a4a2768";
await axios.get(url)
.then((response) => {
const d=response.data.articles[0].source.id;
res.send(d);
}) .catch((error) =>{
console.log(error);
})
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});

Related

Express js get request is showing on the html page

Im new in express.js so i would like to know why when I'm sending a data to client the data is showing in the browser but I'd like to send it in preview please can you take a look what I do wrong?
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/getProducts', (req,res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type','application/json');
res.json(obj);
});
first you need install dependencies like body-parse cors, then you need listen port like this
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/getProducts', (req, res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type', 'application/json');
res.json(obj);
});
app.listen(3000)

Updating Json file in node but fiving previously saved results

I have a simple node script in which I update the db.json file through the form. It updates the file but when I render it in response for a get or post out it gives previous results only.
var cors = require('cors')
const express = require('express');
const app = express();
var jsonfile = require('jsonfile');
var file = './db.json'
var filex = require('./db.json')
app.engine('html', require('ejs').renderFile);
app.use(cors())
const http = require('http');
const port = process.env.PORT || 3000
const bp = require('body-parser')
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))
app.set('view engine', 'html')
// Defining get request at '/' route
app.get('/', function(req, res) {
res.send("<html><head><title>Json</title></head><body><form id='form1' action='/gettingdata' method='post'><input type='text' name='usrid' /><button type='submit' form='form1' value='Submit'>Submit</button></form></body></html>")
});
app.post('/gettingdata',function(req,res){
var user_id = req.body.usrid;
var obj = JSON.parse(user_id)
jsonfile.writeFileSync(file, obj,{flag: 'w'});
res.send('updated');
})
app.post('/api',function(req,res){
res.send(filex)
})
app.get('/api',function(req,res){
res.send(filex)
})
//extra
app.post('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.get('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.listen(port, function(req, res) {
console.log("Server is running at port 3000");
});
It only gives updated results on redeveloping of server.
var filex = require('./db.json')
So, filex only load the file when the server starts. If you try to get the most updated content of file db.json, please re-load the file.
I guess res.send(require('./db.json')) may work as expected.
I have solved this issue using
delete require.cache[require.resolve('./db.json')]

form-data in postman sending Empty body to nodejs

I know this has been asked multiple times, but I have been looking around and still can't find an answer to my problem.
const express = require("express");
require("dotenv").config({
path: ".env",
});
const PORT = process.env.PORT || 5000;
const runDatabase = require("./config/database");
const path = require('path')
const app = express()
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
// routers
const userRouter = require("./router/usersRouter");
const categoryRouter = require("./router/categoryRouter");
const productRouter = require("./router/productRouter");
app.use("/api", userRouter);
app.use("/api", categoryRouter);
app.use("/api", productRouter);
app.listen(PORT, () => {
runDatabase();
console.log(`πŸš€The Backend Server is up and running on port ${PORT}πŸš€`);
});
Here is my code, when sending the request in JSON raw postman a response is what I need but when using a form-data it will return an empty body
app.use(express.urlencoded({ extended: false }));
Try to add this to your middlewares. After express.json()
Change app.use('/', (req, res) => { to app.get('/', (req, res) => {.
app.use is intended for middleware, not normal requests.
Read more about app.use and it's usages here: http://expressjs.com/en/4x/api.html#app.use

Node.js Express GET request does not work even though the same request with POST works fine

GET request return 404 error but POST request to the same url works fine I could not figure out the reason.
this is the server setup:
images.route.js
const express= require('express');
const controllers = require('./controllers');
const router= express.Router();
const upload = require('../../lib/uploads.controller');
router.get('/', (req, res)=> res.send('get request'))
router.post('/', controllers.getAll);
module.exports= router;
route.js
const express = require('express'),
router = express.Router();
const albumRoutes = require('./albums/album.route');
const imageRoutes= require('./images/index');
router.use('/albums', albumRoutes);
router.use('/images', imageRoutes);
module.exports= router;
server.js
let express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
let history = require('connect-history-api-fallback');
const userRoute = require('./routes/router');
const app = express();
app.options('*', cors())
app.use(cors());
app.use(history());
app.use(express.json({limit:
'50mb'}));
app.use(express.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 1000000
}));
app.use('/api', userRoute)
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
I have been searching for a solution but I could not find any reason.
I even installed different REST API apps like postman and insomnia just in case, but it is the same

Socket.io Page Loading Forever

Note - I'm using Pug to render my pages.
My page, when including the script(src="/socket.io/socket.io.js"), does not stop loading.
Here's the relevant content from my app.js.
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
All packages are installed correctly.
In my head tag:
script(src="/socket.io/socket.io.js")
script.
var socket = io();
Yet, my page does not stop loading. What have I done wrong here?
Update:
app.js
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');
const userRouter = require('./routes/userRoutes');
const viewRouter = require('./routes/viewRoutes');
const projectRouter = require('./routes/projectRoutes');
const app = express();
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'));
//MIDDLEWARES
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'overview'));
})
//ROUTES
app.use('/', viewRouter);
app.use('/api/1/users', userRouter);
app.use('/api/1/projects', projectRouter)
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl}.`, 404));
});
app.use(globalErrorHandler);
module.exports = app;
server.js (run by node)
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// mongoose.set('debug',true);
dotenv.config({path: './config.env'})
const app = require('./app');
const DB = process.env.DB.replace('<PASSWORD>', process.env.DBPASS);
mongoose.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(con => {console.log('πŸ”— Connected.')})
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`πŸ“ˆ Running on ${port}.`)
});
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', socket => {
socket.on('greeting', msg => {
console.log(msg);
})
});
http.listen(80);
Now that you've shown your code, this part is wrong:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`πŸ“ˆ Running on ${port}.`)
});
const http = require('http').Server(app);
const io = require('socket.io')(http);
You are creating two separate servers there and binding socket.io to the one that isn't running. Change that above code to this:
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`πŸ“ˆ Running on ${port}.`)
});
const io = require('socket.io')(server);
Earlier attempt to help before OP had shown their actual code.
My guess is that something is messed up in your environment or something is wedged in your OS or something is blocking some requests. To rule things in or out, I would suggest you try this simple app which works just fine for me:
// app.js
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const path = require('path');
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
io.on('connection', socket => {
socket.on("greeting", msg => {
console.log(msg);
});
});
server.listen(80);
and the HTML file temp.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="/socket.io/socket.io.js"></script>
<style>
</style>
</head>
<body>
<button id="myButton">Press Me</button>
<script>
const socket = io();
document.getElementById("myButton").addEventListener("click", () => {
socket.emit("greeting", "hi from client");
});
</script>
</body>
</html>
You put these two files in the same project and you have the server-side socket.io library installed in that project (it should be in node_modules per a normal installation).
Start the server with node app.js in a way that has a server console that you can see output from. Then, from a browser on the same computer, go to http://localhost. It should load a web page with a single button on it. Press that button. You should see a message in the server console that says hi from client each time you press that button.
If this is working, then we would need to see all your project code to see what's wrong with your actual project.
If this isn't working, then we need to know what errors you get. You can try moving this project to a different port in case you have something blocking some things on a particular port. You can reboot your computer in case something in the networking or file system is wedged.

Categories

Resources