Ionic 3+ and Node/Express : Http failure response for (unknown url): 0

放肆的年华 提交于 2021-02-08 11:35:53

问题


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

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');
});

I have tried with app.use(cors()); and also with this :

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.


回答1:


Okay, found out why.

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).

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();
});

Also used cors in each request, like this :

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


来源:https://stackoverflow.com/questions/50860526/ionic-3-and-node-express-http-failure-response-for-unknown-url-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!