Sunday 26 January 2020

Express Sqlite API, cannot access req.body after posting with node-fetch

I have four files,- srv.js: connects both routers to one file, does nothing but listen, use routers, view engines, and bodyParser/- frontend_routes.js: handles all the front end rendering, and redirects/makes requests to the back-end API routes- api_routes.js: the API routes, this hooks up to the sqlite db.- db.js: all database operations are performed in here.​So,I have a route `/create` which exists in the frontend_routes.js, it checks if all the required query properties are present, if not, continue to render the page, else, add all the query properties to an object named body, and then post it to the API route used to create a user, `/users`.the `/users` route exists in the api_routes file, and simply takes all the query properties and sends them to the db.js function.​However,in api_routes, req.body is empty. using postman to do this works completely fine, but doing it with node-fetch isn't. console.log(req.body) returns Object object, console.log(Object.keys(req.body)) returns nothing..? the body property exists if i console.log(Object.keys(req)), but is empty for whatever reason.​I've tried doing the post with the request, axios, and node-fetch libraries to no avail, here's the code for the post request:let body = {user_id: req.query.user_id,username: req.query.username,password: req.query.password,role: req.query.role}fetch("http://localhost:3000/users", {method: "post",body: JSON.stringify(body),headers: {"Content-Type": 'x-www-form-urlencoded'}})have tried with and without stringifying the body, with different content type headers.​and for the love of god, yes i'm using bodyParser, with urlencoded extended:true, I tried json as well with no luck.

Submitted January 27, 2020 at 06:14AM by Cola71t

No comments:

Post a Comment