当你在部署在Heroku上的应用程序尝试使用GET请求时遇到“无法访问GET错误”时,可能是以下几个原因导致的:
const port = process.env.PORT || 3000; // 使用环境变量或默认端口3000
const url = `http://localhost:${port}/api/data`; // 使用正确的端口
// 发送GET请求
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
const express = require('express');
const app = express();
// 添加CORS规则
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://yourdomain.com'); // 允许来自yourdomain.com的访问
res.header('Access-Control-Allow-Methods', 'GET'); // 允许GET请求
next();
});
// 处理GET请求
app.get('/api/data', (req, res) => {
// 返回数据
res.json({ message: 'Hello World' });
});
// 启动服务器
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
请注意,上面的代码中的http://yourdomain.com
应该替换为你要允许访问的域名。如果你希望允许来自任何域的访问,可以将其替换为*
。
希望以上解决方法能够帮助你解决“无法访问GET错误”。如果问题仍然存在,请提供更多的详细信息,以便我们能够更好地帮助你解决问题。