Ionic 3+和Node/Express:(未知网址)的Http错误响应:0 [英] Ionic 3+ and Node/Express : Http failure response for (unknown url): 0

查看:50
本文介绍了Ionic 3+和Node/Express:(未知网址)的Http错误响应:0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从本地mongodb数据库获取数据,但没有成功.

I've been trying to get data from a local mongodb database, with no success.

我已经使用express,cors和mongoose设置了节点服务器.

I've set up a node server using express, cors and mongoose.

根据我在互联网上看到的内容,这应该可以工作:

According to what I've been looking on the internet, this should work :

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var cors = require('cors');
app.use(cors({credentials: true, origin: "*", methods: "GET,HEAD,PUT,PATCH,POST,DELETE", preflightContinue:true}));

mongoose.connect('mongodb://localhost/cats');

const Cat = mongoose.model('Cat',{name:String, color:String});

const kitty = new Cat({name:'Alfred',color:'Black/White'});

// kitty.save().then(()=>{
//     console.log('meow');
// });



app.get('/cats', cors(), function(req, res) { 
    Cat.find({}, function(err, cats){
        if(err){
            res.send(err);
        } else {
            res.send(cats);
        }
    });
});

app.listen(8080,()=>{
    console.log('Listening on 8080');
});

我尝试使用 app.use(cors()); 以及

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Accept');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    } else {
        next();
    }
};
app.use(allowCrossDomain);

,但似乎没有任何效果.

but nothing seems to work.

推荐答案

好,找出原因.

我使用了 ionic serve 命令在手机上进行测试,同时仍在提供程序中保留了 localhost 地址.我必须托管节点服务器和mongo数据库才能使其正常工作(尽管我仍然必须使用本地节点服务器从计算机上的浏览器实验室访问它).

I used the ionic serve command to test on my phone, while still leaving a localhost address in the provider. I had to host the node server and the mongo database for it to work properly (although I still have to use the local node server to access it from the browser lab on my computer).

还更改了现在的cors选项:

Also changed the cors options which now look like :

app.all('*', function(res,req,next){
    res.header('Access-Control-Allow-Origin','*');
    res.header('Access-Control-Allow-Credentials',true);
    res.header('Access-Control-Allow-Methods','PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers','Content-Type');
    next();
});

在每个请求中也使用了cors,例如:

Also used cors in each request, like this :

app.get('/your/route/', cors(), function(req, res) { 
   // logic here
});

这篇关于Ionic 3+和Node/Express:(未知网址)的Http错误响应:0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆