vendredi 3 mai 2019

Empty req.body with ember, express, postgresql app

When making a post request in ember, the request body in the server is having an empty object.

I tried switching from jsonapi in ember to restapi but it did not work. What is getting stored is NULL since title in the pool query is undefined.

Server:

const JSONAPISerializer = require('jsonapi-serializer').Serializer;
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
const cors = require('cors');
const { Pool } = require('pg')
const bodyParser = require('body-parser');

const app = express();
const pool = new Pool({
    user: "zumo",
    host: 'localhost',
    database: 'app',
    password: 'password',
    port: 5432
})

const port = process.env.PORT || 3000
var bookSerializer = new JSONAPISerializer('books', {
    attributes: ['id', 'title']
});

app.use(express.json())
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.get('/books', (req, res) => {
   pool.query('SELECT * FROM books', (error, results) => {
       if(error) {
         throw new Error(error);
       }
       let books = bookSerializer.serialize(results.rows);
       res.status(200).json(books);
   })
})

app.post('/books', (req, res) => {

    try {
        let { title } = req.body;
        console.log(title)
        pool.query(`INSERT INTO books (title) VALUES ($1)`,[title] , (error, result) => {
            if(error) {
              console.log(error);
            }
            let book = bookSerializer.serialize(result.rows);
            res.status(201).send({book});
        })
    }
    catch(e) {
        console.log(e);
    } 
})

app.listen(port, () => {
    console.log('Server up on port: ', port);
})

I am using json-api serializer in ember.




Aucun commentaire:

Enregistrer un commentaire