【问题标题】:Cannot get local file from XMLHttpRequest无法从 XMLHttpRequest 获取本地文件
【发布时间】:2021-08-22 14:08:05
【问题描述】:

我试图通过调用 XMLHttpsRequest() 方法来获取本地 txt 文件。但它一直在控制台中向我发送 404 错误消息。请帮帮我。

这是我的 html 文件

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Ajax1</title>
  </head>
  <body>
    <button id="button" type="button" name="button">Get text files</button>

    <script type="text/javascript">
      document.getElementById("button").addEventListener('click', loadText)

      function loadText(){
        var xhr = new XMLHttpRequest();

        xhr.open('GET', 'sample.txt', true);

        xhr.onload = function(){
          if(xhr.status === 200){
            console.log(xhr.responseText)
          }
        }

        xhr.send(null);
      }
    </script>
  </body>
</html>

本地 txt 文件不在任何文件夹中。 我不知道这是否重要,但这是我的 app.js 文件

const express = require('express')

const app =express()
app.use(express.static("public"))

app.get('/', function(req, res){
  res.sendFile(__dirname+'/ajax1.html')
})

app.listen(3000, function(){
  console.log('server is runing')
})

【问题讨论】:

  • “本地 txt 文件不在任何文件夹内”,因此 404 是正确的。不清楚你想要什么。
  • 你能发布你的目录树吗?在不知道文件在哪里并阅读您的问题的情况下,看起来代码确实是正确的并且没有文件。

标签: javascript ajax asynchronous xmlhttprequest http-status-code-404


【解决方案1】:

这是我的目录树

`>Ajax-beginning
   >node_modules
   •Ajax.html
   •app.js
   •package-lock.jason
   •package.jason

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多