簡體   English   中英

Ajax發布呼叫引發錯誤net :: ERR_UNKNOWN_URL_SCHEME

[英]Ajax post call throwing an error net::ERR_UNKNOWN_URL_SCHEME

我正在嘗試通過ajax從前端到我的Express服務器進行發帖,但出現了錯誤net :: ERR_UNKNOWN_URL_SCHEME。 Ajax的代碼如下

 function sendSteps(encodedLatLangs) { $.ajax({ url: 'localhost:3000/route', type: "POST", dataType: "jsonp", contentType: "jsonp; charset=utf-8", crossDomain:true, data: JSON.stringify({ steps: encodedLatLangs }), success: function (response) { console.log(done); }, error: function (request,error) { console.log('Ajax call gave an error'); } })}; 

我的控制台正在顯示此內容。

這就是我如何處理后端對此端點的發布請求

 router.post('/route',function (req, res) { console.log("Hello Received the Data"); res.send("Hello Received the Data"); //Doing something with the received data }); 

有人能對此有所啟示嗎? 謝謝。

使用JSONP,您只能發送GET請求(JSONP在DOM中插入script標簽)。

您的data應為&key=value字符串, contentTypeapplication/javascript

試試吧:

function sendSteps(encodedLatLangs) {
    $.ajax({
        url: 'localhost:3000/route',
        dataType: "jsonp",
        contentType: "application/javascript; charset=utf-8",
        crossDomain: true,
        data: 'steps=' + encodeURIComponent(JSON.stringify(encodedLatLangs)),
        success: function (response) {
            console.log(done);
        },
        error: function (request, error) {
            console.log('Ajax call gave an error');
        }
    });
};

或使用JSON(如果您是服務器所有者並且可以設置CORS)。

可以通過在響應頭中設置“ Access-Control-Allow-Origin”來完成。 這樣的事情。 有關更多詳細信息,請訪問https://enable-cors.org/server_expressjs.html 。此外,我們還必須從ajax請求中刪除“數據類型”和“內容類型”。

 router.route('/route') .post((req, res, next) => { controllers .post(req.body) .then(data => { res.setHeader('Access-Control-Allow-Origin', req.headers.origin); res.send(message.generateMessage(200, '', data)) }) .catch(err => next(err)) }) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM