I made a chrome extension which calls jQuery’s ajax method:
content-script.js
[...]
$.ajax({
"url": "http://localhost:5000/",
"type": "PUT",
"contentType": "application/json",
"data": { "name": "random object" },
"dataType": "json"
});
[...]
On the server side, I’m trying to fetch the information passed in the data attribute:
web.js
[...]
app.put('/', function(request, response) {
console.log(request.data);
});
[...]
But I’m getting undefined instead. How is the object passed in the data attribute supposed to be retrieved on the server side (Node.js + express.js)?
I also tried console.log(request) and got a LOT of stuff in there, but nothing that looked like the info I passed along in the data attribute…
EDIT
My latest attempt (based on graydsl’s answer) brings the following changes to the code above:
- Added
app.use(express.bodyParser());just beforeapp.put.... - Changed
puttoposteverywhere - Changed
request.datatorequest.body.data
Now, the code does what I want when responding to a form like this:
<form method="post" action="/">
<input name="data" type="text" value="WOO HA" />
<input type="submit" name="submit" value="submit" />
</form>
However it still fails if I revert to using post instead of put (and the browser ends up on http://localhost:5000/?data=WOO+HA&submit=submit for some reason)
It also fails when putting (or posting) with ajax (see code above). When I try it with ajax, I get this on the server:
SyntaxError: Unexpected token ILLEGAL
at Object.parse (native)
at IncomingMessage.<anonymous> (/home/shawn/.node_libraries/.npm/connect/1.8.7/package/lib/middleware/bodyParser.js:135:16)
at IncomingMessage.emit (events.js:61:17)
at HTTPParser.onMessageComplete (http.js:133:23)
at Socket.ondata (http.js:1019:22)
at Socket._onReadable (net.js:683:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)
As others have mentioned, and you’re now doing, you need to use the bodyParser` middleware.
If the request body has a content type of “application/json”,
bodyParserwill parse it into an object, which will be located atrequest.body. Thus in your caserequest.body.nameshould be “random object”.I think you (and several of the previous responders) are mentally hanging up on the fact that jQuery’s
ajaxmethod uses the key name “data” for an object to be sent (serialized as JSON) in the request body, and magically sliding to the assumption that anything on the server side that processes the request will also call that object by the name of “data”. There’s no connection between the two.