Having issues getting page title with meteor.http package

Meteor.http.call( 'GET', 'http://google.com', {}, function( error, response ) {
      if ( error ) {
    console.log( error );
  } else {
    console.log( response );
  }
});

the problem is it keeps showing this error this is my first time using this package so am not sure if i really understand it.

this is the error on my console.

XMLHttpRequest cannot load http://google.com. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access.

Are you making this call on a client or on a server? If on a client, please read about CORS. Basically, browsers are not allowed to make AJAX calls to other servers unless those servers whitelist your domain. This is a security measure to prevent CSRF attacks.

The same does not apply on the server, because it doesn’t check for Access-Control-Allow-Origin headers when making a request.

1 Like

I have a list of urls that users submitted, I want to be able to get the title page and other meta data automatically pls can you tell me how to save the returned data specificly the page title to database.

client/main.js

 if (regex.test(event.target.url.value)==true){
            Websites.insert({
                title: event.target.title.value, 
                url: event.target.url.value, 
                description: event.target.description.value, 
                createdOn: new Date(),
                createdBy: Meteor.user().username,
                thumbsUp: 0,
                thumbsUpBy: "",
                thumbsDown: 0,
                thumbsDownBy: ""
            });
            var url = event.target.url.value;
            Meteor.call("httpRequest", url, params);
        }

server/main.js

Meteor.methods({
    httpRequest: function(url,params) {
        Meteor.http.call( 'GET', url, {}, function( error, response ) {
          if ( error ) {
            console.log( error );
          } else {
            console.log( response );
          }
        })
    }
});

Can we see your complete event handler please?


'submit #js-submitForm-submit': function (event) {
        var regex = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
        if (regex.test(event.target.url.value)==true){
            Websites.insert({
                title: event.target.title.value, 
                url: event.target.url.value, 
                description: event.target.description.value, 
                createdOn: new Date(),
                createdBy: Meteor.user().username,
                thumbsUp: 0,
                thumbsUpBy: "",
                thumbsDown: 0,
                thumbsDownBy: ""
            });
            var url = event.target.url.value;
            Meteor.call("httpRequest", url, params);
        } else {
            $('.invalid').slideDown();
            return false;
        }
    }

is this what you need.

So the event’s target (or currentTarget) contains the event data for the form and is essentially an array of form elements. While you can parse this relatively easily yourself, it’s actually much easier to use jQuery. In Meteor, that’s best done with the template instance jQuery, so something like this:

'submit #js-submitForm-submit'(event, instance) {
  event.preventDefault();
  var regex = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
  if (regex.test(event.target.url.value)==true){
    Websites.insert({
      title: instance.$('input[name="title"]').val(), 
      url: instance.$('input[name="url"]').val(), 
      description: instance.$('input[name="description"]').val(), 
      createdOn: new Date(),
      createdBy: Meteor.user().username,
      thumbsUp: 0,
      thumbsUpBy: "",
      thumbsDown: 0,
      thumbsDownBy: ""
    });
    var url = instance.$('input[name="url"]').val();
    Meteor.call("httpRequest", url, params);
  } else {
    $('.invalid').slideDown();
    return false;
  }
}

Note the instance parameter added to the event and the event.preventDefault() to stop standard form processing action.

Thank a lot for that but can you help me, with the http thing i really need to get it done soon tnks

OK. It wasn’t clear where you felt you had problems.

Your syntax in your method is a little off. Meteor.http is deprecated and you don’t need to use the callback form on the server. You could do something like:

import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

Meteor.methods({
  httpRequest(url, params) {
    try {
      return HTTP.call('GET', url, {}); // or you could use HTTP.get(url, {});
    } catch (error) {
      throw new Meteor.error('error', 'something bad happened')
    }
  },
});

You will need to meteor add http to your project if you haven’t already done it.

      var url = event.target.url.value;
      Meteor.call("httpRequest", url, params);

@robfallows I think after making the changes you suggested I should get a a json data returned to the client right? If that is correct how can I retrieve that data and save it to database.

You get an object (the JSON is decoded for you).

On the client you need to add a callback (or you can use Promises). The callback form would give you something like:

Meteor.call("httpRequest", url, params, (error, result) => {
  if (error) {
    // do something with the error
  } else {
   // do something with the result
  }
});

However, if you just want to store the resulting object in the database, do it on the server within the method.

Meteor.methods({
  httpRequest(url, params) {
    try {
      const result = HTTP.call('GET', url, {}); // or you could use HTTP.get(url, {});
      SomeCollection.insert(result);
    } catch (error) {
      throw new Meteor.error('error', 'something bad happened')
    }
  },
});

As long as you are subscribed to the data on the client, any changes made on the server will get to the client. If you do the insert on the client, it has to be shipped to the server, inserted, and the changes shipped back to the client, which is unnecessary in this case.

1 Like

Hi, some way to make the request from the server enabling the CORS? I have the same problem but I can not establish the connection.

// server side meteor methods
Json( x2) {
    var options = {
      data: x2,
      headers: {
           'content-type': 'application/json',
           'Access-Control-Allow-Origin': '*'
    },
  }
      try {
       var  url = 'https://api.xx.com/xxx-api/4.0/xx.cgi';
       const result  =  HTTP.call('POST', url, options )
      return result;

      } catch (err) {
          console.log(err)
          return false
      }
    }