Search code examples
node.jsvue.jsexpressmongoosefetch-api

Vue.js POST 400 (Bad Request)


My frontend service is like below, I want to send a JSON body to my node.js server backend. The console.log(sample) is shown in console with correct format and with correct data that I want to send, and so is console.log(requestOptions). However, my node backend side keep on return POST 400(Bad Request). Can anyone help me with the code?

Vue service.js

import config from 'config';
import { authHeader } from '../_helpers';

export const sampleService = {
    addNewSample,
}
function addNewSample(sample){
    console.log(sample);
    const requestOptions = {
        method: 'POST',
        headers: authHeader(),
        body: JSON.stringify(sample)
    };
    console.log(requestOptions);
    return fetch(`${config.apiUrl}/samples/newAdd`, requestOptions);
}

Node.js controller.js

const express =require('express');
const router = express.Router();
const sampleService = require('./sample.service');

//routes
router.post('/newAdd', addSample);
//router.get('/:id', getById);

module.exports = router

function addSample(req, res, next){
    console.log(req);
    sampleService.create(req.body)
    .then(() => res.json({}))
    .catch(err => next(err));
}

service.js

const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('_helpers/db');
const Sample = db.Sample;

module.exports = {
    create
};

async function create(sampleParam) {

    console.log(sampleParam);
    const sample = new Sample(sampleParam);

    // save sample
    await sample.save();
}

I've tried this but I don't know how to revised my code to make my backend to return 200 success.


Solution

  • Assuming that authHeader() only returns an object with the Authorization key, you are missing the required Content-Type header to identify the request body as JSON

    const requestOptions = {
      method: "POST",
      headers: {
        ...authHeader(),
        "content-type": "application/json", // 👈 added header
      },
      body: JSON.stringify(sample),
    };
    

    On the server-side, you also need to ensure you have the correct middleware for handling JSON request bodies

    app.use(express.json());