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)
Related
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
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
In Index.js I have added bodyparser and bodyparser url encoder as middleware.
const bodyParser = require("body-parser");
require("dotenv").config();
const PORT = process.env.PORT || 3032;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
In other file I have just console logged the request body and it logs out an empty object.
webhooks.post("/webhooks/", async (req, res) => {
console.log(req.body);
res.send("ok");
});
the res.body is still {}
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");
});
hello im using express for server everything is working find but i am not receiving my data from post method.Iam using body-parser too
const express = require("express")
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/signup", (req,res)=>{
var data = req.body
res.send(req.body)
})
Here is a 100% working code. If it doesn’t work, then tell me how do you make a POST request?
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/signup", (req, res) => {
var data = req.body
console.log(data)
res.send(req.body)
})
app.listen(3000)
Front-end:
axios.post('http://localhost:3000/signup', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});