-1

I am trying to make a simple API in nodeJS, but I hit a wall when trying to post some data.

This is my app.js file:

const express = require('express');
const feedRoutes = require('./routes/feed');

const app = express();

app.use(express.json());

app.use('/feed', feedRoutes)

app.listen(8080)

This is my feed.js routes file:

const express = require('express');
const router = express.Router();

const feedController = require('../controllers/feed');

// GET /feed/posts
router.get('/posts', feedController.getPosts);

// POST /feed/posts
router.post('/post', feedController.createPosts)

module.exports = router

And this is my controller feed.js:

exports.getPosts = (req, res, next) => {
  res.status(200).json({
    posts: [
      {
        title: 'First post',
        content: 'My awesome text',
      }
    ]
  })
}

exports.createPosts = (req, res, next) => {
  const {
    title,
    content,
  } = req.body

  //Create in db later

  res.status(201).json({
    post: {
      id: '1',
      title: title,
      content: content,
    },
    metadata: {
      message: 'Post was created',
    },
  })
}

From what I've read for node.js you need a body parser. Since I am using express 4.16 it is included and I thought I can just solve it with this linen app.use(express.json());

However it looks something like this:

__lookupSetter__:function __lookupSetter__() { … }
constructor:function Object() { … }
hasOwnProperty:function hasOwnProperty() { … }
isPrototypeOf:function isPrototypeOf() { … }
propertyIsEnumerable:function propertyIsEnumerable() { … }
toLocaleString:function toLocaleString() { … }
toString:function toString() { … }
valueOf:function valueOf() { … }
__proto__:null

Any idea why I can't get title and content?

I use postman to make a request with the post method on localhost:8080/feed/post With this in the raw data section

{
    "title": "Look A POST!",
    "content": "Meh"
}

You can find the full code here: https://github.com/Skillvendor/node-js-api

Edit1: This is what i see in the response:

req.body
Object {}
__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , …}

req.body.title
undefined

I fixed the Postman json, still persists the error

Edit2

After enabling corse(Since postman is not in the browser it seems to be considered a CORS problem, though you don't see the error sadly) Adding this solved it:

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});
Lucian Tarna
  • 1,453
  • 2
  • 18
  • 40
  • What did you log under `it looks something like this:`? – lloydaf Jun 23 '19 at 09:20
  • 1
    Your JSON is invalid, which is causing the middleware to throw an error back to the client. Read the response from the client. Fix the two different kinds of errors in your JSON. You might find the UI at https://jsonlint.com/ easier to use for this. Voting to close as off-topic because the problem is caused by typos. – Quentin Jun 23 '19 at 09:23
  • Even the Postman UI sticks an error flag on the JSON input field: https://i.imgur.com/0ETIRW4.png – Quentin Jun 23 '19 at 09:24
  • @Quentin solved that, thank you for jsonlint :D had that extra comma, anyway, the problem still remains – Lucian Tarna Jun 23 '19 at 09:29
  • @theapologist that was the request object, when i type req.body i just get a hash with _prototype. not really what I was hoping for – Lucian Tarna Jun 23 '19 at 09:51
  • Ok Had to enable cors :D – Lucian Tarna Jun 23 '19 at 09:57
  • @LucianTarna — Postman doesn't care about CORS, so that can't be the solution (at least not to the question you asked). – Quentin Jun 23 '19 at 10:41

1 Answers1

-1

You need to use bodyParser middleware. Please take a look at this

agtabesh
  • 508
  • 3
  • 14
  • 1
    I tried with bodyParser.json() also, however express 4.17+ has it included by default that's why i have express.json() same thing as bodyParser.json() – Lucian Tarna Jun 23 '19 at 09:50
  • 2
    I think the way you are sending you post request is a bit wrong! In the body of your post request you need to choose `raw` and then type your request body there such as `{"title": "test title", "content": "test content"}` and then choose `JSON(application/json)` as your content type. – agtabesh Jun 23 '19 at 10:03
  • You are perfectly right! I just forgot to write I was doing that already, the issue itself was cors – Lucian Tarna Jun 23 '19 at 10:09