1
var request = require('superagent');
var url = 'api/server';
request.put(url)
    .set('Content-Type', 'application/json')
    .send('{"name":"tj","pet":"tobi"}')
    .end(function(err, res){
        if (err) throw err;
        console.log(res.text);
    });

above is the code that i use for upload data. If I change put into post, it's not working. I don't know why is that, can anyone help?

Also, actually I want to upload a file. But I cannot use put with .attach('theFile', file) . I've search a lot of example but none of them work for me.

tracer_rock
  • 165
  • 1
  • 3
  • 9

2 Answers2

1

The server handling your request reads both the route (api/server) and the method to determine what response to return. If it's not configured to accept POST requests for that particular route, the request will fail.

Also, superagent does not allow you to use attach and send in the same request. Instead of send use field:

.field('name', 'tj')
.field('pet', 'tobi')

Read the docs for more details.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • yes, you are right. Do you also know how to use the response message? When I get the response message, it's in end(), and I cannot use it else where. the variable I declared outside cannot use inside as well. – tracer_rock Jul 04 '17 at 21:19
0

Probably your server expects PUT and not POST methods on api/server url, check the server source or documentation.

Davorin Ruševljan
  • 4,353
  • 21
  • 27