簡體   English   中英

Ajax 不在同一端口上向本地主機發送請求

[英]Ajax not sending request to localhost on same port

我有一個在localhost:3000運行的節點(快速)服務器。 另一方面,我有一個 HTML ( client.html ) 文件,它由服務器本身在路由/client (該文件作為響應發送)。

我的目標是訪問另一條路線,即/testclient.html頁面上使用 AJAX 調用(由同一服務器提供服務)。 但是,從帖子中可以明顯看出,它不起作用。

不是重復的:到目前為止,我已經嘗試了以下 SO 帖子中給出的解決方案,但沒有成功:

來自本地文件系統(Windows file:///)的 jQuery Ajax 請求 - 雖然
嘗試從 localhost 向 localhost:8000 發送數據時,ajax 調用不起作用
為什么將 CORS 標頭添加到 OPTIONS 路由不允許瀏覽器訪問我的 API?

這是我的源代碼。

服務器.js

const express = require("express")
const bodyParser = require("body-parser")

var app = express()
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json())
...
app.get('/', (req, res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.send('This server does not support GET requests.')
})

app.post('/test', (req, res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.send("response from /test")
})

var port = 3000
var server = app.listen(port)

客戶端.html

<html>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script>
        function init(){
            $.ajax({
                url: 'http://127.0.0.1:3000/test',
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded'
            }).done((data)=>{
                alert(data);
            });
        }
    </script>
    <body onload="javascript:init()">
    </body>
</html>

我曾嘗試同時發送GETPOST請求,但都沒有奏效。

我以前做過這個,只是沒有用nodejs 當我使用requests庫從Python腳本發送requests ,會收到響應,因此服務器似乎工作得很好。

僅供參考,我在 Windows 上。

哪里和/或問題出在哪里?

我嘗試了你的客戶端代碼(在我添加了缺少的 jquery 導入之后),這似乎運行良好(我沒有使用 express):

const server = http.createServer(function (req, res) {
    console.log("logging stuff")
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.write('This server does not support GET requests.')
    res.end();
});

我建議在您的終端上運行 curl 以查看您實際返回的標頭 - curl -I localhost:3000

暫無
暫無

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

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