1

Jersey server code:

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("test")
public class TestPost {

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public String test(@FormParam("name") final String name) {
        System.out.println("name=" + name);
        return "OK";
    }
}

We are using Grizzly, if that matters.

This all works great with curl command, like this:

>curl -v -d "name=test" http://localhost:7777/test
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 7777 (#0)
> POST /test HTTP/1.1
> Host: localhost:7777
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 9 out of 9 bytes
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Content-Length: 2
<
OK* Connection #0 to host localhost left intact

and on the server, we see the name parameter successfully logged, thusly:

name=test

Now... we attempt to do exactly the same trick using Axios:

    const data = {
        name,
    };
    axios.post('http://localhost:7777/test', data, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Length': 9,
            // 'Accept': '*/*',
            // 'User-Agent': 'curl/7.55.1',
            // 'Host': 'localhost:7777',
        }
    }).then((res2, err) => {
        console.log(res2.data);
    }).catch(err => {
        console.error(err);
    });

This request returns "OK"... but now, on the server we see this:

name=null

I added all the same header values to resemble the curl request, but still the passed parameter is null. Omitting the Context-Type header results in a sever error 500, which is also a bit funny.

Note that, using GET rather than POST, everything works fine in both cases.

Marc
  • 1,812
  • 4
  • 23
  • 36
  • try converting data to strinig , like `axios.post('http://localhost:7777/test', JSON.stringify(data), { ....});` – Bourbia Brahim Sep 08 '19 at 09:15
  • 1
    Have a look https://stackoverflow.com/a/55719674/3461055 – Arif Khan Sep 08 '19 at 09:47
  • Sure enough! it is necessary to ´querystring.stringify(data)´ ... for some ungodly reason which is contrary to what axios docs would have us believe. https://www.npmjs.com/package/axios – Marc Sep 08 '19 at 17:56

1 Answers1

0

So apparently, it is necessary to ´querystring.stringify(data)´ ... for some unholy reason understood only by the Dark Lord himself. Obviously, this is totally contrary to what the axios docs would have us believe:

DO NOT:

DON'T DO THIS!

DO:

axios.post('/user', querystring.stringify({
    firstName: 'Fred',
    lastName: 'Flintstone'
  })).then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  });

Yeah. Just.... wow.

Marc
  • 1,812
  • 4
  • 23
  • 36