PUT请求访问被阻止

时间:2019-08-04 22:44:52

标签: javascript kotlin xmlhttprequest httprequest netty

我一直在尝试通过PUT请求更新某个表中的值。但是,我不断收到这些错误,而且我不确定为什么:

OPTIONS http://localhost:8080/api/ping/1001 404 (Not Found)

Access to XMLHttpRequest at 'http://localhost:8080/api/ping/1001' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

每当我将请求切换到GET请求时,它就起作用。

我的后端

 embeddedServer(Netty, 8080) {

       routing {
            get("/api/ping/{num?}"){
                var nsq_num: Int = Integer.valueOf(call.parameters["num"]?: "1001")
                var stmt: Statement? = null
                var resultset: ResultSet? = null
                val obj = arrayListOf<SRTEntry>()
                        .....
                        .....
                val gson = Gson()
                var str = gson.toJson(obj)
                call.response.header("Access-Control-Allow-Origin", "*")
                call.respondText(str, ContentType.Application.Json)
            }
            put("/api/ping/{num?}"){
                var nsq_num: Int = Integer.valueOf(call.parameters["num"]?: "1001")
                var stmt: PreparedStatement? = null
                var resultset: ResultSet? = null
                val obj = arrayListOf<SRTEntry>()
                        .....
                        .....
                val gson = Gson()
                var str = gson.toJson(obj)
                call.response.header("Access-Control-Allow-Origin", "*")
                call.respondText(str, ContentType.Application.Json)
            }

调用PUT请求的前端

var url = "http://localhost:8080/api/ping/1001";
var req = new XMLHttpRequest();
req.onload = function(event){
    if (parseInt(req.status, 10) != 200) {
        return;
    }
    var text = req.responseText;
    console.log(text);
}
req.open("PUT", url, true);
req.send();

调用GET请求:

var url = "http://localhost:8080/api/ping/1001";
var req = new XMLHttpRequest();
req.onload = function(event){
    if (parseInt(req.status, 10) != 200) {
        return;
    }
    var text = req.responseText;
    console.log(text);
}
req.open("GET", url, true);
req.send();

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

添加

install(CORS){
            method(HttpMethod.Put)
            anyHost()
        }

在路由修复之前,如下所示:

install(CORS){
    method(HttpMethod.Put)
    anyHost()
}
routing {
   get("/api/ping/{num?}"){
   var nsq_num: Int = Integer.valueOf(call.parameters["num"]?: "1001")
   var stmt: Statement? = null
   var resultset: ResultSet? = null
   ...

您可以从https://dev.to/effingkay/cors-preflighted-requests--options-method-3024

获取有关它的更多信息。