使用代理服务器解决 jQuery 跨域访问本地主机问题
使用代理服务器解决 jQuery 跨域访问本地主机问题
由于安全原因,浏览器限制了跨域访问本地主机。如果要在 jQuery 中访问本地主机,可以使用代理服务器来实现。
步骤
-
启动代理服务器: 在本地主机上启动一个代理服务器,可以使用 Node.js 或其他语言实现。代理服务器监听一个可访问的端口,例如 8080。
-
使用代理服务器地址: 在 jQuery 中使用代理服务器的地址作为请求地址,例如:
$.getJSON('http://localhost:8080/data.json', function(data) {
console.log(data);
});
- 转发请求: 在代理服务器中,将请求转发给本地主机。例如使用 Node.js 实现:
var http = require('http');
http.createServer(function(req, res) {
var options = {
hostname: 'localhost',
port: 3000,
path: req.url,
method: req.method
};
var proxy = http.request(options, function(response) {
response.pipe(res);
});
req.pipe(proxy);
}).listen(8080);
其中,代理服务器监听的端口为 8080,将请求转发给本地主机的端口为 3000。这样就可以在 jQuery 中跨域访问本地主机了。
原文地址: https://www.cveoy.top/t/topic/n92Q 著作权归作者所有。请勿转载和采集!