express.js get method cannot get req.body value - javascript

I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});

The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine

Related

Can't connect to an api endpoint in my express server

I am new to express and currently having issues connecting to an api
below is my code
const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const flash = require("connect-flash");
const fetch = require("node-fetch");
const axios = require("axios");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
let sessionOptions = session({
secret: "Javascript is so cool",
store: MongoStore.create({ mongoUrl: process.env.CONNECTIONSTRING }),
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true },
});
app.use(sessionOptions);
app.use(flash());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("public"));
app.set("views", "views");
app.set("view engine", "ejs");
const router = require("./router");
const apiRouter = require("./apiRouter");
const options = {
url: "https://rms.pythonanywhere.com/api",
method: "",
json: {},
};
app.use("/", router);
app.use(options.url, apiRouter);
module.exports = app;
Below is the file i created for routes that goes to the api
const express = require("express");
const apiRouter = express.Router();
const request = require("request");
const fetch = require("node-fetch");
const userController = require("./controllers/userController");
const pageController = require("./controllers/pageController");
apiRouter.post("/user/create", async function (req, res) {
const api_url = "https://rms.pythonanywhere.com/api";
const fetch_res = await fetch(api_url, options);
const json = await fetch_res.json();
res.json(json);
});
module.exports = apiRouter;
When i submit my registration form i want it to send it post request to the url of the api and recieve its response. But whenever i send a post request to the api url it returns an error of (can't send post request to /user/create)
What i really want to achieve is to connect to this api link (rms.pythonanywhere.com/api) and be able to direct my routes for registration and login with some other routes to the api. I've been battling with this for over a week now. Please guys help me out, I'm new to express
Thanks in advance guys
I think your express app is unable to find the apiRouter so, you need to use express router first with the help of express.use() method.
You can add below line to your code.
express.use("/", apiRouter);
Thanks guys for your response. Although none was actually the solution, but it gave me a clue of what i needed to do.
What i used in solving my issues was axios. i required("axios") after installing from npm store and den i used it in my apiRouter.post("/user/create") route. Below is what i did to solve the issue
apiRouter.post("/register", async function (req, res) {
const api_url = "https://rms.pythonanywhere.com/api";
axios.post(api_url + "/user/create/", {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
user_type: req.body.user_type,
username: req.body.username,
}). then((response) =>{}).catch((error){})
});
I was able to send the data's from my post request made in apiRouter.post(/register) and recieved the success response in my then() and error response in my catch() block.

Nodejs Express req.body is empty and header null

I am working on retrieving a post request body so that i can add the arguments in the body to my database.
At first I was getting an error SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>) but i added this line applctn.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies and now i get an empty body.
My code looks like this :
const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");
const applctn = express();
applctn.use(bodyParser.urlencoded({extended: true}));
applctn.post("/hl7_message", function(req, res) {
var jsonObj = JSON.stringify(req.body);
console.log(req);
When i add ```app.use(bodyParser.json()); // to support JSON-encoded bodies
```SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>)
Any advise /tips on how i can retrieve the body contents will be appreciated.
my response
You forgot to add applctn.use(bodyParser.json()). Here is the solution :
const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");
const applctn = express();
applctn.use(bodyParser.json());
applctn.use(bodyParser.urlencoded({extended: true}));
applctn.post("/hl7_message", function(req, res) {
console.log(req.body);
res.send({code:200,message:"success"})
})
applctn.listen(3000,function(){
console.log("running");
});

Express js bodyparser post req.body not working?

I try to build an api with express js post request. I use body-parser for req.body . But after sending post request i couldn't get any message still loading then show timeout. where is my problem please take a look my code.
I am testing it from postman and use on header content-type application/json.
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config/config.js').get(process.env.NODE_ENV);
const mongoose = require('mongoose');
const app = express();
mongoose.connect(config.DATABASE)
const {Book} = require('./models/book')
app.use(bodyParser.json())
// Post Book
app.post('api/book', (req,res)=>{
let book = new Book(req.body)
book.save((err, doc)=>{
if(err) return res.status(400).send(err);
res.status(200).json({
post:true,
bookId: doc._id
})
})
})
Now error show- cannot post /api/book
but when i try with this below code its working--
const book = new Book({ name: 'Zildjian' });
book.save().then(() => console.log('data save'));
Change your route from api/book to /api/book - add a leading /.
Also, it looks like it might be timing out as it can't get passed your cookie-parser middleware.
You have passed the function:
app.use(cookieParser)
...but you need to invoke it:
app.use(cookieParser())
You will also need to import it:
const cookieParser = require('cookie-parser')
...or just remove it completely if you don't need it.
I hope this helps.

Error setting cookie and getting a json response with router.post in express, node.js

I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js

Graphql: Must provide query string

I have a simple express graphql server:
const schema = require('./schema');
const express = require('express');
const graphqlHTTP = require('express-graphql');
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/graphql', graphqlHTTP(req => {
return ({
schema,
pretty: true,
})
}));
const server = app.listen(9000, err => {
if (err) { return err; }
console.log(`GraphQL server running on http://localhost:${9000}/graphql`);
});
And my request looks like:
Any help?
(Please don't close it as duplicate because the other post does not provide enough info on how the user solved it)
You need to specify application/json in your Content-Type header -- you currently have text/plain. You've included the body parser middleware on the server, but it relies on that header in your request to know when it needs to actually parse the response into JSON.

Categories

Resources