Javascript 反应:Axios 网络错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45980173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React: Axios Network Error
提问by Mirakurun
This is my first time using axios and I have encountered an error.
这是我第一次使用 axios,遇到了一个错误。
axios.get(
`http://someurl.com/page1?param1=1¶m2=${param2_id}`
)
.then(function(response) {
alert();
})
.catch(function(error) {
console.log(error);
});
With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn't call the callback, but instead it caught an error.
使用正确的 url 和参数,当我检查网络请求时,我确实从我的服务器得到了正确的答案,但是当我打开控制台时,我看到它没有调用回调,而是捕获了一个错误。
Error: Network Error Stack trace: createError@http://localhost:3000/static/js/bundle.js:2188:15handleError@http://localhost:3000/static/js/bundle.js:1717:14
错误:网络错误堆栈跟踪:createError@ http://localhost:3000/static/js/bundle.js:2188:15handleError@ http://localhost:3000/static/js/bundle.js:1717:14
采纳答案by jacobhobson
If Creating an API Using NodeJS
如果使用 NodeJS 创建 API
您的 Express 应用程序需要使用 CORS(跨源资源共享)。将以下内容添加到您的服务器文件中:
// This should already be declared in your API file
var app = express();
// ADD THIS
var cors = require('cors');
app.use(cors());
For fuller understanding of CORS, please read the Mozilla Documentation on CORS.
为了更全面地了解 CORS,请阅读关于 CORS的Mozilla 文档。
回答by Mahdieh Shavandi
my problem was about the url I was requesting to. I hadnt't inserted http://at the begining of my url. I mean I was requesting to a url like 92.920.920.920/api/Tokeninstead of http://92.920.920.920/api/Token. adding http://solved my problem.
我的问题是关于我请求的网址。我没有http://在我的 url开头插入。我的意思是我请求的是一个像92.920.920.920/api/Token而不是http://92.920.920.920/api/Token. 添加http://解决了我的问题。
回答by Tiago Barroso
In addition to @jacobhobson answer, I had also used some parameters to made it work.
除了@jacobhobson 的回答之外,我还使用了一些参数来使其工作。
app.use(cors({origin: true, credentials: true}));

