【问题标题】:XMLHttpRequest Returns 404 Even Though File Exists即使文件存在,XMLHttpRequest 也会返回 404
【发布时间】:2019-10-13 11:30:06
【问题描述】:

这就是我的项目的文件结构。 Voice、Text 和 Template 是文件夹。

我运行python app.py,当我转到本地主机http://0.0.0.0:8080/ 时,我可以看到index.html 页面,内容由app.py 输入。

index.html 中有从voice.txt 输入的文本,如果我在文本编辑器中查看voice.txt,我可以看到app.py 中的一个循环每20 秒成功地向其附加更多文本。

我遇到的问题是尝试将更新后的 voice.txt 文本放入 index.html 的正文中。我正在尝试使用 XMLHttpRequest 来做到这一点。这是index.html标签中的相关代码:

function UpdateText() {
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200) {
        // Code goes here
        document.getElementById("main").innerHTML = this.responseText;
        console.log(statusText);
        console.log(responseText);
    }
};

xhttp.open("GET", "../Text/voice.txt", true);
xhttp.send();

};

当我运行 index.html 时正确显示,但当它尝试更新文本时,我在终端中收到以下错误消息:

127.0.0.1:64013 - - [28/May/2019 00:55:10] "HTTP/1.1 GET /Text/voice.txt" - 404 Not Found

我可能是错的,但此时我相当确定xhttp.open() 中的文件路径实际上应该是一个 URL(这是我第一次使用 XMLHttpRequest,我看到的每个教程都只有文件名仅此而已),在这种情况下,我不确定如何链接到voice.txt。我为此使用了 web.py 库,这是app.py 的相关部分:

urls = (
"/", "index",
)

indexpath = "/Users/[USERNAME]/torch/torch-rnn/voice/Template/"
render = web.template.render(indexpath)

class index(object):
def GET(self):
    the_voice = open(voicepath, "r+").read()    
    return render.index(the_voice)

if __name__ == "__main__":
app = web.application(urls, globals())
app.run()

我觉得解决方案可能涉及更改 urlsrender 变量中的某些内容,但我已经为此转了几个小时,但我没有想法。

我的尝试

我首先想到的是将一个名为 voice.txt 的虚拟文件放入 index.html 旁边的模板文件夹中,然后更改 XMLHttpRequest 中的文件路径以反映这一点,但我仍然收到相同的错误消息。

【问题讨论】:

    标签: javascript python ajax xml web.py


    【解决方案1】:

    您的网络服务器知道单个 URL“/”,并在被询问为“https://:8080/”时将其返回。这就是您在urls =() 位中列出的所有可能值。

    因此,您尝试通过 Web 界面获取其他任何内容都会失败。如果您想让网络服务器检索您的 voice.txt 文件,您需要在urls 中包含它或与之匹配的内容,然后让该类获取并发送voice.txt 文件。 (请注意,文件本身不在Text 文件夹中,它们可以在任何地方,如myDirectory 所述。)

    例如,

    urls = ( "/", "index",
             "/Text/(.*)", "get_file")
    
    class get_file(object):
        def GET(self, filename):
            the_file = open(myDirectory + '/' + filename, "r").read()
            return the_file
    

    可能会做你想做的事(或给你一些想法)。通过使用urls 中的正则表达式,任何http get 像'/Text/foo'、'/Text/voice.txt'、'/Text/ant_eater.jpg' 将尝试读取文件('foo'、' voice.txt', 'ant_eater.jpg') 在myDirectory 描述的目录中,并将该文件返回给用户。

    如果您提供不同类型的文件(如我的示例),您还应该为内容类型设置标题,但这是一个不同的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 2016-11-03
      相关资源
      最近更新 更多