javascript - Axios.get 返回状态码 400 无法找出问题所在(SODAapi)
问题描述
无法弄清楚我的 axios 调用有什么问题。任何帮助将非常感激。
所以我有一个搜索栏 onClick 会将搜索词发送到编译 Api 查询字符串的函数。
const SearchForm = () => {
const [searchTerm, setSearchTerm] = useState({
searchTerm : "",
boro: ""
});
const handleChange = e => {
const { value, name } = e.target;
setSearchTerm((e)=>{
return {
...searchTerm,
[name] : value
}
});
};
const handleSubmit = async (e) => {
e.preventDefault();
debugger
const res = await SodaApi.searchResta(searchTerm.searchTerm, searchTerm.boro);
console.log(res)
setSearchTerm("");
}
return (
<form className="SearchForm" onSubmit={handleSubmit}>
<label htmlFor="searchBar">Restaurant Name:</label>
<input type="text"
id="searchBar"
name="searchTerm"
placeholder="Enter Restaurant Name"
value={searchTerm.searchTerm}
onChange={handleChange}
/>
<label htmlFor="boro">Borough: <span>*</span></label>
<select id="boro"
name="boro"
value={searchTerm.boro}
onChange={handleChange}
required
>
<option value="" defaultValue disabled hidden>Select a Boro</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Manhattan">Manhattan</option>
<option value="Staten Island">Staten Island</option>
<option value="Bronx">Bronx</option>
<option value="Queens">Queens</option>
</select>
<button className="SearchFormButton" type="submit">Search</button>
</form>
)
}
export default SearchForm;
这是编译功能
class SodaApi {
static token;
static async searchResta (searchTerm, boro) {
const headerOptions = {
headers : {
'X-App-Token' : `${config.MY_APP_TOKEN}`
}
};
const queryOptions = `$query=SELECT camis,dba,boro,building,street,zipcode,phone,cuisine_description,inspection_date,action,violation_code,violation_description,critical_flag,score,grade,grade_date,record_date,inspection_type,latitude,longitude WHERE dba like '%${searchTerm.toUpperCase()}%' AND boro = '${boro}'`;
const sodaApiQueryString = config.NYC_RESTA_API_URL + queryOptions;
const results = await axios.get( sodaApiQueryString, headerOptions);
const cleanedResults = consolidate(results);
return cleanedResults
};
这是我返回的示例查询字符串。我打电话给 Soda Api。
https://data.cityofnewyork.us/resource/43nn-pn8j.json?$query=SELECT%20camis,dba,boro,building,street,zipcode,phone,cuisine_description,inspection_date,action,violation_code,violation_description,critical_flag,score,grade,grade_date,record_date,inspection_type,latitude,longitude%20WHERE%20dba%20like%20%27%STAR%%27%20AND%20boro%20=%20%27Brooklyn%27
我回来的错误是这个
GET https://data.cityofnewyork.us/resource/43nn-pn8j.json?$query=SELECT%20camis,dba,boro,building,street,zipcode,phone,cuisine_description,inspection_date,action,violation_code,violation_description,critical_flag,score,grade,grade_date,record_date,inspection_type,latitude,longitude%20WHERE%20dba%20like%20%27%STAR%%27%20AND%20boro%20=%20%27Brooklyn%27 400 (Bad Request)
Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
我没有得到的是,如果我在 INSOMNIA 中发送了相同的查询字符串,我会得到状态码 200,并且我会得到我想要的数据。但是为什么当我用我的搜索栏发送它时,我得到了一个 400 错误。我尝试取出我的标头令牌,尝试使用不同的查询进行搜索。我的应用程序再次不起作用,但如果我使用相同的查询字符串,我会从我的 chrome 控制台返回并使用 INSOMNIA 发送它,它可以工作。
怎么来的??
解决方案
查询字符串中的%
字符未正确编码。它们应该被编码为%25
. 请参阅https://developers.google.com/maps/documentation/urls/url-encoding
使用 Axios 确保这一点的最简单方法是使用params
配置。那里的任何键/值都将进行 URL 编码。
const options = {
headers : {
'X-App-Token': config.MY_APP_TOKEN
},
params: {
"$query": `SELECT camis,dba,boro,building,street,zipcode,phone,cuisine_description,inspection_date,action,violation_code,violation_description,critical_flag,score,grade,grade_date,record_date,inspection_type,latitude,longitude WHERE dba like '%${searchTerm.toUpperCase()}%' AND boro = '${boro}'`
}
};
const results = await axios.get(config.NYC_RESTA_API_URL, options);
推荐阅读
- mysql - Mybatis 执行慢
- networking - 计算机网络中的“延迟”和“延迟”有什么区别?
- sql - 如何将计算的 SQL 列转换为小数点后 2 位?
- firebase - Google Cloud Functions 如何检测活动实例的数量?
- python - 如何在 matplotlib 中绘制 200 行(时间序列)并使其在 x 轴上可读?
- python - 如何处理 ParserErrors 并继续解析?
- javascript - 在循环中选择动态元素 id
- sql - 在 kdb 中,在多个不等式的列上是否存在等价的左连接(如 asof 连接的可修改版本)?
- c# - 编写重载运算符的更简单方法 +/-
- node.js - 试图了解node、npm和git是如何集成在一起的