首页 > 解决方案 > Jersey POST 参数值始终为空,但适用于 curl 命令

问题描述

泽西服务器代码:

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";
    }
}

我们正在使用 Grizzly,如果这很重要的话。

这一切都适用于 curl 命令,如下所示:

>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

在服务器上,我们看到 name 参数成功记录,因此:

name=test

现在......我们尝试使用 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);
    });

这个请求返回“OK”......但是现在,在服务器上我们看到了:

name=null

我添加了所有相同的标头值以类似于 curl 请求,但传递的参数仍然为空。省略Context-Type标头会导致服务器错误 500,这也有点搞笑。

请注意,使用 GET 而不是 POST,在这两种情况下一切正常。

标签: javanode.jsjerseyaxiosgrizzly

解决方案


显然,有必要“querystring.stringify(data)”……出于某些只有黑魔王本人才能理解的邪恶原因。显然,这与axios 文档让我们相信的完全相反:

不要:

不要这样做!

做:

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

是的。只是……哇。


推荐阅读