Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS issue when call algo nodejs api from ionic(angular) app (response for preflight has invalid HTTP 404) ) #12

Closed
lubancafe opened this issue Oct 11, 2017 · 8 comments

Comments

@lubancafe
Copy link

I am trying to make a mobile app with ionic3( based on angular4). it could also be a progressive web app (PWA). When call algo node api, I get following CORS error,

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.

@lubancafe
Copy link
Author

After hours' digging with Jon's prompt support, I figure out that this CORS issue does exist for node client (algo nodejs api 0.3.10), might affect many angular developers who try to adopt algorithmia. But no such CORS issue for JS client( https://algorithmia.com/v1/clients/js/algorithmia-0.2.0.js).

For JS client, I made a simple pen here, http://jsfiddle.net/bund/phw612Lx/
jsfiddle-jsapi-cors-ok

As we can see, the preflight request&response are OK(200) following by actual response w/ OK .

But for node client, the OPTIONS request is not getting right server response which leads to a 404 CORS error.
ionic-nodejsapi-cors-404

I am guessing this CORS issue is either underlying algo node client code (when wrapping xhr headers) or somewhere inside stream-http within augular.

Either case, I would like to report this issue here for tracking.

For now, ionic/angular app (valid for ionic1.x, 2.x, 3.x) can still use js api to consume algorithmia. Happy coding.

@anowell
Copy link
Contributor

anowell commented Oct 11, 2017

If you look closely, you'll see that using the browser javascript client uses a different URL:

algorithmia.com/v1/algo/demo/Hello
algorithmia.com/v1/web/algo/demo/Hello  <- CORS-enabled route

We use a separate, more-limited CORS-enabled route to reduce the scope of how API keys can be used since embedding API keys in a public website makes it easy for anybody to make API calls on your behalf. The biggest difference is that their are currently no CORS-enabled routes for accessing data.

As you discovered, only the brower JS client currently uses that endpoint. It sounds like your immediate issue is unblocked, but I'm gonna keep this open for tracking the unification of the javascript and nodejs clients. I see a couple steps to getting there:

  1. detect if running in a browser, and if so, use the CORS routes
  2. improve error messages if using CORS but attempting to use the Data API methods
  3. consider an HTTP client that abstracts away the browser vs node HTTP apis (e.g. superagent)

@tusharbudhe0302
Copy link

I am referring this URL app running different port to separate Angular 2 with NodeJS
Front End Code :

`
var baseUrl = ‘https://usdf13v0412_dev_tushar:3000/';

let xhr = super.build();

xhr.withCredentials = true;

xhr.open(‘GET’, baseUrl, true);

xhr.send();

xhr.onload = function() {

var responseText = xhr.responseText;

console.log(responseText);

// process the response.

};

xhr.onerror = function() {

console.log(‘There was an error!’);

};
ExpressJS:

const originsWhitelist = [‘http://usdf13v0412_dev_tushar:4200/'];

const corsSettings = {

origin: function (origin, callback) {

const isWhitelisted = originsWhitelist.indexOf(origin) !== -1;

callback(null, isWhitelisted);

},

credentials: true

};

app.use(cors(corsSettings));

app.get(‘/’,

ensureAuthenticated,

function (req, res,next) {

console.log(‘redirect to UI’);

res.redirect(‘http://usdf13v0412_dev_tushar:4200/');

});

app.get(‘/login’,

passport.authenticate(passportSamlConfig.passport.strategy, { failureRedirect: ‘/login’ }),

function (req, res, next) {

console.log(‘Login done!’);

next();

});

app.post(‘/assert’,

passport.authenticate(passportSamlConfig.passport.strategy, { failureRedirect: ‘/login’ }),

function (req, res) {

//console.log(‘Recive user details from saml done!’);

res.redirect(‘/’);

res.end();

});

function ensureAuthenticated(req, res, next) {

console.log(‘aruth middleware!’);

if (req.isAuthenticated()) {

console.log(‘isAuthenticated middleware sucess ! ‘);

next();

} else {

console.log(‘isAuthenticated middleware failed ! ‘);

return res.redirect(‘http://usdf13v0412_dev_tushar:3000/login');

}

}`

I am using passport-saml for authenticating users to SSO. It was working fine when both were running on same port.

I am not able to redirect to login. If I use URL in browser ‘http://usdf13v0412_dev_tushar:4200/' It’s going to my middle-ware.It’s logging this code:

console.log(‘isAuthenticated middleware failed ! ‘);

If I us URL in browser http://usdf13v0412_dev_tushar:3000/xyz I am able to redirect to login.

@anowell
Copy link
Contributor

anowell commented Feb 22, 2018

@tusharbudhe0302 I suspect your comment was intended for an issue on some other project. Is that accurate?

@Fil
Copy link

Fil commented Nov 26, 2018

I had s similar CORS issue when I tried this module in @observablehq (https://beta.observablehq.com/@fil/hello-umap) ; I found a hacky solution with:

Algorithmia = require("https://algorithmia.com/v1/clients/js/algorithmia-0.2.0.js")
  .catch( () => window.Algorithmia )

ideally, it would be

Algorithmia = require("algorithmia")

@MoMoWongHK
Copy link

I am have a CORS problem with my reactjs application.
I would like to make an api call in my react app, but the error return:
Access to fetch at 'https://api.algorithmia.com/v1/algo/nlp/AutoTag/1.0.1?timeout=300' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is my code:

var Algorithmia = require("algorithmia");

export async function getKeywordTags(input) {
    const al = Algorithmia.client("MY_API_KEY")
        .algo("nlp/AutoTag/1.0.1?timeout=300") // timeout is optional
        .pipe(input)
        .then(function(response) {
            console.log(response.get());
            return response.get()
        });
}

@peckjon
Copy link

peckjon commented Mar 25, 2019

Hi @MoMoWongHK -- Could you try using Fil's solution above?: #12 (comment)

The problem is that Ionic needs the Browser JS client, not the NodeJS client.

Just replace require("algorithmia") with:

require("https://algorithmia.com/v1/clients/js/algorithmia-0.2.0.js")
  .catch( () => window.Algorithmia )

@peckjon peckjon closed this as completed Mar 25, 2019
@rajat2502
Copy link

rajat2502 commented Jul 23, 2020

Hey @MoMoWongHK did you got how to import it in React to prevent CORS error?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants