user3877654
user3877654

Reputation: 1283

What is wrong with this PUT statement?

I am trying to write a PUT statement using Nodejs and Express, but am failing. I have included the entire error message here. There is also a GET application, but that is simpler and seems to work as expected.

server.js

app.use('/data', express.static('/views/data'));


app.put('/data/1-1', (req, res) => {
  let body = "";
  req.on('data', function (chunk) {
    body += chunk;
  });
  
  req.on('end', function () {
    do something  
  });
}); 

commandline

curl -X PUT http://localhost/data/1-1 -H "Accept: application/json" -H "Content-Type: application/json" --data-binary '[{"key": 1}]'

error

ReferenceError: data is not defined
    at app.put (/home/w/server.js:172:15)
    at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/w/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/w/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)
    at /home/w/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/w/node_modules/express/lib/router/index.js:335:12)
    at next (/home/w/node_modules/express/lib/router/index.js:275:10)
    at /home/w/server.js:146:5
    at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)

Upvotes: 0

Views: 77

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43481

Using express, you can access the request body in req.body.

So in your case:

app.put('/data/1-1', (req, res) => {
  console.log(req.body);
  // do something
  res.send(''); // sends an empty response
}); 

Upvotes: 1

Related Questions