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
Related
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)
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
So, I got this error while try to ready my application for production. So, my index.js code is
const app = express();
const port = 8000;
const cors = require('cors');
const db=require('./config/mongoose');
const path = require('path')
//library used
const passport = require('passport');
const passportJWT = require('./config/passport-jwt-strategy');
const bcrypt = require('bcrypt');
//middleware
app.use(express.json());
app.use(cors());
//use routes
app.use('/', require('./routes'));
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.join(__dirname, 'frontend', 'build', 'index.html')))
app.listen(port, async function(err){
if(err){
console.log(`error in running of server;${err}`);
}
console.log(`server is running on port:${port}`);
});
This is my file structure. So, If someone know, why this is happening. please reply.
Thanks
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)