Nagaraj M
Nagaraj M

Reputation: 447

Ajax Post with express js get req parameter error

I am using the ajax to post the data from javascript front end to express js has backend server. How i can get the posted data, in express js api method req params. I am facing issue when i try to parse the request data below is my code.Please help me to solve this

            $.ajax({
                url: "http://localhost:8080/api/save_user/",
                type: "POST",
                crossDomain: true,
                data: { name: 'Justin', number: '662***' },
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    var resp = JSON.parse(response)

                },
                error: function (xhr, status) {
                    alert("error");
                }
            });    


Express Js server side

const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())


//deploy the smart contract
app.post('/api/save_user', (req, res) => {
    console.log((JSON.parse(req.body)));
    res.send({})
})

Error Log

SyntaxError: Unexpected token n in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/node_modules/body-parser/lib/types/json.js:158:10)
    at parse (/node_modules/body-parser/lib/types/json.js:83:15)
    at /node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/raw-body/index.js:224:16)

Upvotes: 0

Views: 50

Answers (1)

Kevyn Klava
Kevyn Klava

Reputation: 316

The problem is that jquery expect you to pass an string with the json inside. try like this:

            $.ajax({
                url: "http://localhost:8080/api/save_user/",
                type: "POST",
                crossDomain: true,
                data: JSON.stringify({ name: 'Justin', number: '662***' }),
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    var resp = JSON.parse(response)

                },
                error: function (xhr, status) {
                }
            });

Upvotes: 1

Related Questions