[英]405 method not allowed using Tomcat
我是Web開發的新手,而且這個問題已有一段時間了。 我嘗試了很多在SO和其他地方建議的方法,但是沒有運氣。 無論如何,我會解釋我在做什么。
我正在嘗試一個簡單的練習,我有一個簡單的HTML頁面,該頁面接受一個城市名稱,然后單擊“提交”按鈕,將向我顯示該城市的天氣。 HTML代碼如下:
<body>
<form>
<div>
<label for="city">City</label>
<input id="city" type="text" name="city">
</div>
<div>
<input id="submitButton" type="button" name="submitButton" value="Get weather!" onclick="send()">
</div>
</form>
<script type="text/javascript" src="CityWeather.js"></script>
</body>
這個HTML文件調用了我的JS腳本,該腳本將處理對OpenWeatherMap API的調用並顯示結果。 JS的代碼如下(請注意,我故意省略了api_key,但實際的URL確實有它):
function send() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=london&APPID=<api_key>", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var jsonResponseText = xhttp.responseText;
//var response = JSON.parse(jsonResponseText);
console.log(xhttp.readyState);
console.log(xhttp.status);
console.log(jsonResponseText);
}
現在,當我第一次嘗試僅通過啟動HTML文件來獲取結果時,遇到了CORS問題,我意識到我不應該通過文件URL(file://)來調用API。 因此,我下載了Tomcat 9.0,並將HTML和JS文件都放置在Tomcat的webapps文件夾中。 然后,我啟動了Tomcat並啟動了該頁面。 但是,我得到了下面提到的異常:
OPTIONS http://api.openweathermap.org/data/2.5/weather?q=london&APPID=<api_key> 405 (Method Not Allowed)
Failed to load http://api.openweathermap.org/data/2.5/weather?q=london&APPID=<api_key>: Response for preflight has invalid HTTP status code 405.
我嘗試使用以下條目更新CATALINA_BASE / conf / web.xml文件,
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
重新啟動服務器,然后再次嘗試,但仍然沒有運氣。 有人可以指出需要做些什么來幫助我嗎? 我正在為此練習使用Chrome。 我也嘗試使用IE,但沒有運氣。
更新1:我嘗試更改api調用。 我沒有使用openweathermap API,而是嘗試使用GIT API來獲取我的存儲庫。
function send() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://api.github.com/users/bhavyas66", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var jsonResponseText = xhttp.responseText;
//var response = JSON.parse(jsonResponseText);
console.log(xhttp.readyState);
console.log(xhttp.status);
console.log(jsonResponseText);
}
在這種情況下,我沒有得到上面的異常,但是狀態停留在1且狀態打印為0。響應也為空。 但是,當我打開Chrome網絡窗口時,可以看到“預覽”標簽下有響應
嘗試“ POST”方法,通常與POST方法同時出現405個錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.