xhr.open()函数中的URL参数做什么?

编程入门 行业动态 更新时间:2024-10-10 17:23:15

xhr.open()函数中的URL参数<a href=https://www.elefans.com/category/jswz/34/1765403.html style=做什么?"/>

xhr.open()函数中的URL参数做什么?

我正在编写一些服务器软件,并且已经使用非常简单的HTML文件对其进行了测试。当我打开一个新的XMLHttpRequest POST请求时,URL参数似乎没有什么区别。谁能告诉我?如果有帮助,请参见以下代码:

浏览器HTML文件:

<!DOCTYPE html>
<html>
    <body>
        <title>This is a title!</title>
        <p id="paragraph">
            Hello World!
        </p>
        <script>
            setTimeout(() => {
                var http = new XMLHttpRequest();
                var jsonToSend = {
                    "name": "Steve Smith",
                    "age": 25,
                    "isMale": true
                };
                http.open("POST", "", true);
                http.setRequestHeader("Content-Type", "application/json");
                http.send(JSON.stringify(jsonToSend));
            }, 3000);
        </script>
    </body>
</html>

服务器代码(node.js)

const http = require("http");
const fs = require("fs");
const port = 80;

http.createServer((request, response) => {
    if (request.method == "GET") {
        try {
            var newUrl = request.url.substring(1);

            if (request.url == "/") {
                newUrl = "test.html";
            }

            response.writeHead(200, "OK", {"Content-Type": "text/html"});
            response.write(fs.readFileSync(newUrl).toString());
        } catch (error) {
            response.writeHead(404, "Not Found", {"Content-Type": "text/html"});
            response.write("<h1>404 not found</h1>");
        }
        response.end();
    } else if (request.method == "POST") {
        var body = "";

        request.on("data", (chunk) => {
            body += chunk.toString();
        });
        request.on("end", () => {
            console.log(JSON.parse(body));
            response.statusCode = 200;
            response.end(body);
        });
    }

    console.log(request.method + ":");
    console.log("  URL: " + request.url);
    console.log("  Status code: " + response.statusCode);
}).listen(port, () => {
    console.log("Listening on port " + port);
});
回答如下:

它设置请求的URL。

这似乎没有什么不同,因为您编写的Web服务器对于POST请求不关注URL

更多推荐

xhr.open()函数中的URL参数做什么?

本文发布于:2024-05-07 08:50:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:做什么   函数   参数   xhr   open

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!