java - 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,在这两种情况下一切正常。
解决方案
显然,有必要“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);
});
是的。只是……哇。
推荐阅读
- neo4j - neo4j - declare variables that are available for node creation in FOREACH clause and also for the RETURN clause
- javascript - 将两个对象数组的相同属性合并为一个
- css - How do I change the link of an image using CSS
- laravel - Outlook 中的 SVG 图形问题
- azure - 使用查询字符串从 Azure CDN 清除单个文件缓存
- node.js - Update nested array objects in MongoDB
- visual-studio - Prevent Visual Studio from leaking pdb path in compiled exe
- python - 403 使用 pypodio2 禁止来自 podio API 的响应
- java - Reformat custom date from string
- html - 如何在父div中显示具有相同输入框的新div