首页 > 解决方案 > 使用 xhr.open('post',url,true) 找不到文件 URL - 状态:404 node js

问题描述

尝试通过 上传图像时XMLHttpRequest(),无法理解通过 . 访问文件的正确 URL 是什么xhr.open(...)

按照示例获取服务器端代码和所有内容..

var xhr = new XMLHttpRequest();

  xhr.open('post','../../../../server/routes/saveImage.js',true);
  xhr.onload = function() {
    if(this.status ==200) {
      resolve(this.response);
    } else {
      reject (this.statusText);
    }
  };

项目目录是这样的

另外关于路径,让我知道是否有更方便的方法来检查要在 url 中使用的访问路径或绝对路径。

标签: node.jsreactjspathxmlhttprequest

解决方案


我认为在许多层面上都存在概念问题。

首先,当您使用 XHRing(ajax) 时,一个 url 意味着您正在从 CLIENT SIDE 访问该 url。因此,假设您有一个应用程序和 HTTP 发布或获取一个 url。你有来自客户端的那个文件吗?答案显然是否定的。假设您将应用程序托管在:

http://localhost/myapps/app

因此,当您访问./someFile.txt时,../someFile.txt../../someFile.txt实际上是在请求

./someFile.txt-> http://localhost/myapps/app/someFile.txt
../someFile.txt-> http://localhost/myapps/someFile.txt
../../someFile.txt-> http://localhost/someFile.txt 

现在,对于你的问题。您需要在某处托管Server Side上传代码。该示例假设服务器端代码托管在例如,http://localhost/upload并使用xhr.open('post','/upload',true);

您需要了解requireing 或importing 或fs.readFile文件正在内部访问路径。但是当您托管应用程序时,任何像 Ajax(XHR) 这样的客户端代码都会从外部访问 url。


推荐阅读