如何使用Axios向CountriesNow API发送POST请求获取罗马尼亚城市列表?
错误原因
- 你手动将请求参数封装为了JSON字符串,且未在请求头中声明
Content-Type: application/json,后端接口无法正确解析请求体内容,因此判定缺少country参数。 - Postman中发送请求时,选择JSON格式的请求体后会自动携带对应的Content-Type请求头,因此可以正常请求。
修复方案
推荐直接使用JS对象作为请求参数,Axios会自动完成JSON序列化以及请求头的配置,无需手动处理:
var data = { "country": "romania" }; axios({ method: 'post', url: 'https://countriesnow.space/api/v0.1/countries/cities', data: data }) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error); });
如果你需要手动传递JSON字符串,需要补充对应请求头:
var data = JSON.stringify({ "country": "romania" }); axios({ method: 'post', headers: { 'Content-Type': 'application/json' }, url: 'https://countriesnow.space/api/v0.1/countries/cities', data: data }) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error); });
内容的提问来源于stack exchange,提问作者Diana
相关产品推荐
相关产品推荐

