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')]
Related
I'm trying to recreate a Note Taking App using Express. My code follows the instructor's example but when I deploy it and try to add a new note I get the error cannot get/api/name...I am not sure what I am doing wrong.
enter code here
const fs = require('fs');
const path = require ('path');
const express = require('express');
const dbJson = require('./db/db.json')
const {v1 : uuidv1} = require('uuid');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static("public"));
app.get('/notes', (req, res) => {
res.sendFile(path.join(__dirname, './public/notes.html'));
});
app.get('/api/notes', (req,res) => {
const dataNotes = fs.readFileSync(path.join(__dirname, './db/db.json'), "utf-8");
const parseNotes = JSON.parse(dataNotes);
res.json(parseNotes);
});
Add at the end: app.listen(PORT);
That will work. The problem was that you didn't start the server
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");
});
I am new to node and express js.Today I am learning and I have initialized node server as:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const PORT = 3000
const api=require('./routes/api')
const app = express()
app.use(bodyParser.json())
app.use(cors())
api.use('/api',api)
app.get('/', function(req, res) {
res.send('Hello from server')
})
app.listen(PORT, function(){
console.log("Server running on localhost:" + PORT)
});
I have created a folder routes inside server folder and there is api.js file which has GET method to test, whether the api is working or not.Inside api.js I have,
const express = require('express')
const router=express.Router()
router.get('/', (req, res) => {
res.send('from Api Route');
})
module.exports=router
I type node server and it is displaying me :
Server running on localhost:3000
But,when I try to get the url: http://localhost:3000/api,it is displaying me:
And,in api.js file in the arrow function sublime is showing me error in red marker as:
Replace api.use('/api',api) with app.use('/api',api)
I want to write a very simple web-app with express and node.js.
The app only has a index.html with a form. When the form ist POSTed, the node.js server should react by writing the input value in a txt file.
In the browser, the index.html file then should be reloaded to be ready to submit the next form.
I managed to get everything to work except the part where the index.html file is reloaded after the request is handled.
The index.html is located in the 'www' folder.
What is the best way to do it?
This is my app.js:
var express = require('express')
var app = express()
const fs = require('fs');
const bodyParser = require('body-parser');
app.use(express.static('www'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Express app listening at http://%s:%s', host, port)
})
server.on('request', (req, res) => {
if (req.method === 'POST') {
collectRequestData(req, res => {
console.log(res);
});
}
// Here the index.html should be reloaded
});
//This function only writes the form data to txt-file, I don't know if it is relevant here
function collectRequestData(request, callback) {}
Try redirecting to the index after you handle the post:
server.on('request', (req, res) => {
if (req.method === 'POST') {
collectRequestData(req, res => {
console.log(res);
});
}
// Here the index.html should be reloaded
res.redirect('/');; --->Redirect to index here.
});
Here's the reference: https://expressjs.com/en/4x/api.html#res.redirect
I am writing a simple MEAN app, and I am currently working on the routes.
In my server.js, I have
var express = require('express');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
var sizeOf = require('image-size');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
require('./app/models/Purchase');
require('./app/models/Seller');
require('./app/models/User');
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
// mongoose.connect(db.url); // connect to our mongoDB database
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
// routes ==================================================
var routes = require('./app/routes/routes');//(app); // pass our application into our routes
var price = require('./app/routes/pricing');
var processing = require('./app/routes/processing');
var uploads = require('./app/routes/uploads');
var seller = require('./app/routes/seller');
app.use('/', routes);
app.use('/price', price);
app.use('/processing', processing);
app.use('/uploads', uploads);
app.use('/seller', seller);
// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port);
exports = module.exports = app;
Then, in my route, I have
var express = require('express');
var mongoose = require('mongoose');
var Seller = mongoose.model('Seller');
var router = express.Router();
router.get('/', function(req,res){
res.json({message: 'youre in router.get'});
});
router.post('/registerSeller', function(req,res,next){
console.log('You made it all the way to seller route!');
res.json({message: "you did it"});
next();
});
module.exports = router;
When I start my node server, everything goes well. When I use Postman to POST to the above route, it just 'hangs' and eventually gives an error message that it cannot connect. In Postman, I select 'POST' to http://localhost:8080/seller/registerSeller.Clicking 'code', I get
POST /seller/registerSeller HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Postman-Token: 070cb9b3-992a-ffd6-cede-c5b609bc9ce5
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Looking at the browser's developer tools, it shows a POST being made, and then after a while, it also reads that the POST failed.
Could anyone tell me what I'm doing wrong? Thank you.
The problem is that you are responding and then trying to call the next() function in the router stack.
router.post('/registerSeller', function(req,res,next){
console.log('You made it all the way to seller route!');
return res.send({message: "you did it"});
//next(); remove this shit.
});
This should work. Express middlewares go in order. So if you need to have a middleware to be called before this function, then you have to put it before in the stack. If you need to do something after this function, forget about the res.json... part.