简体   繁体   中英

Accessing String on Node.js Server from Ajax Post Request

This is my first project working with ajax and node.js and so far all my POST requests have been done through form submissions.

I am now trying to use $.ajax to send a POST and pass the string 'cocktailid' for the server.js to use after a div click() .

I was wondering what the easiest way to accomplish this would be.

Ajax code

$(".col-sm").click(function(){
  //Append to console a log that cocktail div has been clicked.
  console.log("Cocktail Clicked.");
  console.log(this);

  //Create variable to hold id of cocktail div clicked
  var cocktailid = $(this).attr('id');
  cocktailid = cocktailid.replace(/\s+/g, '_');
  cocktailid = cocktailid.replace(/'/g, '');
  alert(cocktailid);

  $.ajax({
   type: 'POST',
   url: '/adddrink',
   data: { "field1": cocktailid},
   dataType: "json",
   cache: false,
   contentType: "application/json",
   success: function(data) {
    console.log('success');
    console.log(cocktail + 'sent.');
    console.log(JSON.stringify(data));
   }
  });
})
};

Server.js

app.post('/adddrink', function(req, res){
console.log(req.body);
});

I have tried to send the data in a few different formats and had different problems, currently my server is showing the following error:

SyntaxError: Unexpected token # in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:157:10)
    at parse (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:83:15)
    at /home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:224:16)
    at done (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:160:13)
    at endReadableNT (_stream_readable.js:1101:12)
    at process._tickCallback (internal/process/next_tick.js:152:19)

Right now I just want to show I can access the string on the node server.

I've tried looking around for a solution and after my attempts I expect I've really over complicated what I am trying to achieve, any help would be greatly appreciated!

You have to use: JSON.stringify on data

$.ajax({
  type: 'POST',
  url: '/adddrink',
  data: JSON.stringify({
    "field1": cocktailid
  }),
  dataType: "json",
  cache: false,
  contentType: "application/json",
  success: function(data) {}
});

Without it the payload is field1=yes instead of {"field1":"yes"} that's why you're getting SyntaxError: Unexpected token # in JSON at position 0 because you weren't posting a valid JSON.

For a more detailed error, you can add an error handling middleware after body-parser to handle JSON errors.

app.use(bodyParser.json());

app.use((err, req, res, next) => {

    // Body parser middleware Error
    if(err instanceof SyntaxError) {

        // err.body contains the actual body that was posted
        // which won't be a valid JSON.
        console.error(`Invalid JSON: ${err.body}`);

        return res
            .status(400) // Bad request
            .send({
                message: 'Invalid JSON'
            });

    }

    next();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM