在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 使用koa接受post請求報錯404 這是什么原因

使用koa接受post請求報錯404 這是什么原因

ajax

 xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        if (xmlhttp.responseText) {
          alert(' 驗證成功')
        }
      }
    }
    xmlhttp.open('POST', 'http://localhost:3000/e', true)
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xmlhttp.send(data)
    alert(data.email)

koa2

router.post('/e', async (ctx, next) => {
    
        var name = ctx.request.body.email || '';
        ctx.response.set("Access-Control-Allow-Origin", '*');
        ctx.response.body = '用戶名或密碼錯誤';
        console.log(name);
        
});

已經(jīng)確定服務(wù)器端正確接受了請求 但是接收到的狀態(tài)碼是404這是什么原因?

回答
編輯回答
浪蕩不羈

我使用Koa2。看了個帖子,發(fā)現(xiàn)Koa默認(rèn)返回狀態(tài)status默認(rèn)是404,前端發(fā)送POST請求的時候,如果不主動改變ctx.body的值,那么打印你API返回的ctx可能是這樣:

"request": {
    "method": "POST",
    "url": "/api/wkcs/upd",
    "header": {
        "host": "127.0.0.1:3000",
        "connection": "keep-alive",
        "content-length": "2",
        "accept": "application/json, text/javascript, */*; q=0.01",
        "origin": "http://127.0.0.1:3000",
        "x-requested-with": "XMLHttpRequest",
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36",
        "content-type": "application/json",
        "referer": "http://127.0.0.1:3000/edit?wkid=59f583d6-a4d8-450d-97c7-657e21853d68",
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6",
        "cookie": "myusername=eyJteXVzZXJuYW1lIjoiYmVhdHMifQ=="
    }
},
"response": {
    "status": 404,
    "message": "Not Found",
    "header": {}
},
"app": {
    "subdomainOffset": 2,
    "proxy": false,
    "env": "development"
},
"originalUrl": "/api/wkcs/upd",
"req": "<original node req>",
"res": "<original node res>",
"socket": "<original node socket>"

注意看response,如果你不對ctx中的參數(shù)做任何更改,response始終會是Koa默認(rèn)的404 —— 即便你的后臺邏輯一切正常!

如果像那位答主說的,將ctx.body改寫一下body的話,此處response返回值就是正常的200。


總結(jié)一下:

一、如果瀏覽器直接報404,基本上是你的URL沒寫對,或是POST參數(shù)配錯了。

二、如果瀏覽器沒有報錯,只是你查看后臺發(fā)現(xiàn)response返回404,那么你后臺API邏輯可能仍可以正常運行,只是因為沒有操作Koa的ctx.body,修改其默認(rèn)的status。此時,你POST提交的data會被封裝進ctx.request.body.你的數(shù)據(jù)字段名里,后臺可以讀取,正常完成你的業(yè)務(wù)邏輯。

如果還有問題,拿IDE給后臺加斷點,看看能否讀到ctx.request.body.你的數(shù)據(jù)字段名這里的數(shù)據(jù)吧。

2017年5月27日 14:26
編輯回答
心上人

服務(wù)器收到了請求因為域名正確 404報錯以為具體路徑有誤

2018年8月11日 05:14
編輯回答
莫小染

路由沒有寫錯,但是如果沒有輸出響應(yīng),確實為404

ctx.body = '用戶名或密碼錯誤';

試試

2018年7月3日 02:35