简体   繁体   中英

XMLHttpRequest - relative or absolute path?

I'm trying to make HTTP tests in my local server.

On my HTML file, I link src="scripts/scriptedHTTP.js :

   var req = new XMLHttpRequest();
   req.open("GET", "file.txt", false);
   req.send(null);
   console.log(req.responseText);

I serve on localhost:8000 with python -m SimpleHTTPServer .

file.txt is on the same path as scriptedHTTP.js

http://localhost:8000/scriptedHTTP.html gets me Error 404 .

If I run scriptedHTTP.js with node , I get XMLHttpRequest is not defined .

What I am doing wrong?

XMLHttpRequest will form the request path using the page domain (if you don't set it manually), so in this case you just need to specify the complete path of your file.txt :

var req = new XMLHttpRequest();
req.open("GET", "scripts/file.txt", false);
req.send(null);
console.log(req.responseText);

Note that XMLHttpRequest is a feature of web browsers so is not available in NodeJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM