0

I'm trying to put some data in mysql database using sails js API, Here is my data which I'm sending via ajax call

{"person":{"name":"Sahasrangshu Guha","address":"Dlf It Park Ii Block 1a, Plot No. Ii-F/1, Action A, Ericsson Kolkata","phoneNumber":"9830612244"}}

Here is the ajax call header

{ 'Content-Type': 'application/json', 'responseType': 'json' }

My sails js controller is as follows

module.exports = {

addPerson: function (req, res) {
    if (req.method == 'POST' && req.param('person', null) != null) {
        console.log(req.param('person'));
        Person.create(req.param('person'), (error, person) => {
            if(error) {
                res.send('Error:Sorry!Something went Wrong');
            } else {
                res.send('Successfully Created!');
            }
        });

            // Error handling
            // if (err) {
            //     res.send('Error:Sorry!Something went Wrong');
            // } else {}
            //     res.send('Successfully Created!');
            //     //res.redirect( ‘person/view/’+model.id);
            // }

    }
    else {
        res.send('Error:Sorry!Data Wrong');
    }
}
}

And my sails js model looks like below

module.exports = {
  tableName: 'person',
  primaryKey: 'id',
  attributes: {
  name: {
    type: 'string',
    required: true
  },
  address: {
    type: 'string',
    required: true
  },
  phoneNumber: {
    type: 'string',
    required: true
 }
  }

};

I'm alaways having the following error whenver I'm making a POST request to my sails js API

{error: SyntaxError: Unexpected token E in JSON at position 0 at JSON.parse ()

Any idea to solve this? I have tried sending object rather than JSON data but the same error pursues.

1 Answer 1

1

While returning the response I think an Object is being expected instead of String here res.send(errObj); where error obj should be something like

{
success: false,
status: 400,
message : 'Error:Sorry!Something went Wrong'
}

Or send the message with status code

res.status(response.status || 500).send(response)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks , I was thinking the problem was in my request body but actually the problem was for my response data.
I'm glad it solved your query, cud u upvote my answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.