Error while instanciating Restivus "Cannot find name 'Restivus' " - meteor

I imported restivus using :
meteor add nimble:restivus
And while using Restivus I encounter this error on meteor startup :
"Cannot find name 'Restivus' ".
I can although GET requests but I wonder if it impacts the behavior of the app.
Here is the code used :
if (Meteor.isServer) {
// Global API configuration
var Api = new Restivus({
apiPath: 'api/',
prettyJson: true
});
}
When receiving POSTs my request.body and my bodyParams are empty :
Api.addRoute(':id/test', {
post: function () {
var id = this.urlParams.id;
console.log("Body contains : ");
console.log(this.bodyParams);
return {
status: 'success',
url : 'post test from id: '+id,
body : this.bodyParams
};
}
});
Does anyone know how to make this error disappear and if this is linked to the POST body problem ?

If you use Meteor 1.4+ you can try to import Restivus to your file with something like this:
import Restivus from 'nibmle:restivus';

The problem with post body being empty was caused by the request I made :
I wasn't specifying the Content-type header.
Once I specified the "Content-Type": "application/json" it worked.
The "Cannot find 'Restivus' " Error is still here though.

Your code looks ok. Here is some code from a server-only file that I am using:
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true,
apiPath: 'restAPI/',
defaultHeaders: { 'Content-Type': 'application/json;encoding="UTF-8"' }
});
// Generates: GET, POST on /api/items and GET, PUT, DELETE on
// /api/items/:id for the Items collection
Api.addCollection(Policy);
Perhaps you should move your code to the server directory? I am on Meteor 1.3.4.

Related

Symfony : Access-Control-Allow-Origin ('security.token_storage)

I work with Symfony and I try to get the user id from another website (ajax). But it does not works !
I have this error in my browser :
Access-Control-Allow-Origin
My code is :
$response->headers->set('Access-Control-Allow-Origin', '*');
/* That does not works and returns : 'NOOOO !!!' but, no error */
if($this->get('security.authorization_checker')->isGranted('ROLE_USER'))
{
$usertosend = $this->get('security.token_storage')->getToken()->getUser();
$id = $usertosend->getId();
$response->setData(array('user'=>$id));
}
else
{
$response->setData(array('user'=>'NOOOO !!!'));
}
/* That works :*/
$usertosend = $this->get('security.token_storage')->getToken()->getUser();
/* That does not works and returns : Access-Control-Allow-Origin error*/
$id = $usertosend->getId();
As soon as I use a getter of the user, there is an error.
If I don't use the getter, there is no error.
There is no problem with the origin domain.
Ok, The problem came from the cookies. So I add these headers :
$response->headers->set('Access-Control-Allow-Origin', 'http://localhost');
$response->headers->set('Access-Control-Allow-Methods', 'get');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, *');
And I add this mention in my ajax method :
xhrFields: {withCredentials: true},
$.ajax({
type: 'get',
url: 'http://myurl.com',
xhrFields: {withCredentials: true},
success: function(user){
alert(user.user);
}
I hope, it will help next users.
Thanks for your help :)
See you
You can use NelmioCorsBundle in your symfony project for adding headers CORS in they response of your application.
This is a very simple and quickly installation. This is a standard bundle for construct a symfony API Rest Application which called with external application.
NelmioCorsBundle

JSZip and cfs:collection in Meteor app

So, Im using udondan:jszip, cfs:collection,
cfs:standard-packages and
cfs:filesystem packages in my meteor app. The problem is that I cant store my zip files in the FS.COllection. Here is some of the code :
//Defining the collection
Reports = new FS.Collection('reports',{
stores: [new FS.Store.FileSystem('reports', {path: "~/public"})]
});
//Trying to add a file to the collection
var zip = new JSZip();
Reports.insert(zip);
After running the code Im getting this error:
Error: DataMan constructor received data that it doesn't support
Is there any way to make those packages work with each other ?
The JSZip object is not a file by itself. You can generate a file from it with the generateAsync function. The file type you'll want to create depends on if you want this to run on the client or server and how you want to use this file. The file types supported by both libraries are: (as per documentation, I haven't tested all these myself)
Blob object (client only): { type: 'blob' }
Uint8Array: { type: 'uint8array' }
ArrayBuffer: { type: 'arraybuffer' }
Buffer object (server only): { type: 'nodebuffer' }
So for example this should work:
zip.generateAsync({ type: 'arraybuffer' })
.then(function (content) {
Reports.insert(content);
});

Meteor audit-argument-checks

I have a Meteor project where I'm using audit-argument-check. I'm getting an error message
Error: Did not check() all arguments during publisher 'document
I'm know this is related the audit-argument-check not being able to check all arguments. But as far as I'm concerned, I checked all of them. Concrete, I have defined a collection 'documents' and attached a SimpleSchema. As part of iron-router, I have the following:
Router.route('customerDocumentShow', {
template: 'customerDocumentShow',
path: 'customer/documents/:_id',
waitOn: function () {
return Meteor.subscribe('document', this.params._id);
},
data: function () {
return Documents.findOne(this.params._id);
}
});
So I'm passing only the documentId (this.params._id). On the server, I have defined a method:
Meteor.methods({
documentsReadMethod: function(documentId){
check(documentId, String);
var documentItem = Document.findOne(argument);
if (!documentItem) {
throw new Meteor.Error(500, 'Error 500: Not Found', 'No documents found.');
}
return documentItem;
}
});
So I'm checking to documentId in the server method. So not sure why I'm getting this error message.
Note: One thing I'm not entirely sure about though is how I need to call this method (right now, it's documentsReadMethod_. I'm not explicitly calling (on the client):
Meteor.call(documentsReadMethod, this.params_id);
as I'm using autoform, collection2 and simpleschema. I've been spending the entire weekend, but have no clue. Any idea's ?
Note: the code is on github: https://github.com/wymedia/meteor-starter-base
The problem is in the publish. You didn't check the id here:
https://github.com/wymedia/meteor-starter-base/blob/master/server/publications/documents.js#L16
Just add check(id, String); line 16 and it should work.
I have the same problem with another tuto !
Answer found at check is not defined in meteor.js : since Meteor v1.2, you have to add this package:
$ meteor add check

How to get site's name from WP API

I'm trying to get WordPress website title using javascript and WP API plugin
I didn't find any example on how to get the site's name but I found the variable name under the entities section in the developer guide
function _updateTitle(documentTitle) {
document.querySelector('title').innerHTML =
documentTitle + ' | '+ $http.get('wp-json/name');
}
The output string of $http.get('wp-json/name') is [object Object]
Does anyone know how to use fix this?
You didn't get enough context. What's $http? What happens when you go to wp-json/name directly in your browser? Here's what I see:
[{
"code":"json_no_route",
"message":"No route was found matching the URL and request method"
}]
Here's a simple example to get you the title:
var siteName;
$.getJSON( "/wp-json", function( data ) {
siteName = data.name;
});
See more elegant solution here https://wordpress.stackexchange.com/a/314767/94636
response will not contain extra data like:
authentication: []
namespaces: ["oembed/1.0", "akismet/v1", "acf/v3", "wp/v2"]
routes: {/: {namespace: "", methods: ["GET"],…},…}
timezone_string: ""
...
_links: {help: [{href: "http://v2.wp-api.org/"}]}

Meteor/Iron-Router: how to define routes using data from settings.json

For the URL to which a route applies I have a part defined in settings.json, like this
baseUrl: '/private'
My settings are published and accessible through the collections 'Settings' (on the client). So I tried the following:
Meteor.subscribe('settings');
Deps.autorun(function () {
var settings = Settings.findOne():
if (settings) {
Router.map(function () {
this.route('project', {
path: settings.baseUrl + '/:projectId,
controller: 'ProjectController'
});
});
}
});
The problem is that during initialisation the data is not yet on the client available, so I have to wait until the data is present. So far this approach doesn't work (yet). But before spending many hours I was wondering if someone has done this before or can tell me if this is the right approach ?
Updated answer:
I published solution in repository : https://github.com/parhelium/meteor-so-inject-data-to-html
. Test it by opening url : localhost:3000/test
In this case FastRender package is useless as it injects collection data in the end of head tag -> line 63.
Inject-Initial package injects data in the beginning of head tag -> line 106.
Needed packages:
mrt add iron-router
mrt add inject-initial
Source code:
Settings = new Meteor.Collection("settings");
if (Meteor.isClient) {
var settings = Injected.obj('settings');
console.log(settings);
Router.map(function () {
this.route('postShow', {
path: '/'+settings.path,
action: function () {
console.log("dynamic route !");
}
});
});
}
if (Meteor.isServer){
if(Settings.find().count() == 0){
Settings.insert({path:"test",data:"null"});
}
Inject.obj('settings', Settings.findOne());
}
Read about security in the bottom of the page : https://github.com/gadicc/meteor-inject-initial/
OLD ANSWER :
Below solution won't work in this specific case as FastRender injects data in the end of head tag. Because of that Routes are being initialized before injected data is present.
It will work when data from Settings collection will be sent together with html.
You can do that using package FastRender.
Create file server/router.js :
FastRender.onAllRoutes(function(path) {
// don't subscribe if client is downloading resources
if(/(css|js|html|map)/.test(path)) {
return;
}
this.subscribe('settings');
});
Create also publish function:
Meteor.publish('settings', function () {
return Settings.find({});
});
The above code means that if user open any url of your app then client will subscribe to "settings" publication and data will be injected on the server into html and available for client immediately.
I use this approach to be able to connect many different domains to meteor app and accordingly sent proper data.

Resources