I have an Ember CLI app that uses Rails as a backend. The code appears to be fine, and if I visit localhost:3000, it displays the JSON output just fine. However, Ember does not display this data.
Here is what I have so far:
// ember/app/adapters/application.js
import DS from "ember-data";
export default DS.ActiveModelAdapter.extend({
namespace: 'api'
});
// ember/app/controllers/data_keys.js
export default Ember.ArrayController.extend({
sortProperties: ['name']
});
// ember/app/models/data_key.js
export default DS.Model.extend({
name: DS.attr('string')
});
// ember/app/routes/data_keys/index.js
export default Ember.Route.extend({
controllerName: 'data_keys',
model: function() {
return this.store.all('data_key');
}
});
// rails/app/controllers/api/data_keys_controller.rb
class Api::DataKeysController < ApplicationController
def index
render json: DataKey.all
end
end
// rails/app/serializers/data_key_serializer.rb
class DataKeySerializer < ActiveModel::Serializer
attributes :id, :name
end
// rails/config/routes.rb
Rails.application.routes.draw do
namespace :api do
resources :data_keys
end
end
To run the app, I run the Rails side with rails s, then in another terminal tab I run ember server --proxy http://localhost:3000.
Is there something obvious that I'm missing? I know that Ember CLI version 0.0.39 had proxy uses, but I'm using Ember CLI 0.0.40.
ember -v
version: 0.0.40
node: 0.10.28
npm: 1.4.21
Here's an example of the JSON returned by the server:
{
"data_keys": [{
"id": 1,
"name": "foo"
}, {
"id": 2,
"name": "bar"
}]
}
I think that when you use DS.Store#all you're only filtering the records that are already in the store. You'll want to use DS.Store#find in order to get the records from the server.
export default Ember.Route.extend({
controllerName: 'data_keys',
model: function() {
return this.store.find('data_key');
}
});
Also, your ember files should use dashes rather than underscores.
Related
I have a React frontend using Rails 6 as an API. Webpacker is configured to package image files in app/javascript/media to app/javascript/packs. As far as I can tell, Webpack is creating the packs correctly; the packs folder contains my bundle.js, bundle.js map, and the .svg file bundled by webpack. Bundle.js is running fine, but when I try and import the image in a component, I'm getting a routing error stating:
ActionController::RoutingError (No route matches [GET] "/img.svg")
All of the questions I've seen about this mention that static assets don't get served by Rails in production mode without further configuration, but I have Rails in development mode and webpack-dev-server running.
Here's my webpack.config.js:
const path = require('path');
module.exports = {
context: __dirname,
entry: './frontend/app_name.jsx',
output: {
path: path.resolve(__dirname, 'app', 'javascript', 'packs'),
publicPath: path.resolve(__dirname, 'app', 'javascript', 'packs'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '*']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
query: {
presets: ['#babel/env', '#babel/react']
}
},
},
{
test: /\.(png|svg)?$/,
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
},
devtool: 'source-map'
};
Update: My routes.rb contains:
Rails.application.routes.draw do
root 'static#index'
namespace :api, defaults: { format: :json } do
resources :search, only: [:index]
end
end
and my static controller is
class StaticController < ApplicationController
def index
render :index
end
end
Should requests for static assets compiled by webpacker even be making it to the backend in a one page app?
I'm building a Rails API using the gem 'graphql' and want to access this GraphQL API using a Gatsby.js front-end. I've attempted to use gatsby-source-apiserver plugin and gatsby-source-graphql, but neither of them seem to work. (The API works fine when I do queries using the GraphiQL app on my local machine.)
Is there a better Gatsby.js source plugin what will work well with a Rails API using the gem 'graphql', which provides a single endpoint, http://localhost:3000/graphql? And if so, how should I configure that plugin in gatsby-config.js, etc? (BTW, I'm using a Postgres database which I intend to deploy to Heroku -- I'd thought about pursuing hasura, but I'm not sure if that's the best option.)
In the Rails API in routes.rb, I've set up post "/graphql", to: "graphql#execute" to route to GraphqlController. Here is the execute method in the Controller...
def execute
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
# current_user: current_user,
}
result = GraphqlRailsSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue => e
raise e unless Rails.env.development?
handle_error_in_development e
end
When I attempt to render the json: result, result is: #<GraphQL::Query::Result #query=... #to_h={"errors"=>[{"message"=>"No query string was present"}]}> for either of the front-end set-ups I cite below....
In my Gatsby.js front-end, when I use gatsby-source-apiserver, in gatsby-config.js, I have...
{
resolve: 'gatsby-source-apiserver',
options: {
typePrefix: 'internal__',
url: `http://localhost:3000/graphql`,
method: 'post',
headers: {
'Content-Type': 'application/json'
},
data: {
},
name: `posts`,
entityLevel: `data.posts`,
payloadKey: `body`,
}
},
...and I get his error in my console when I run gatsby develop...
TypeError: Cannot read property 'data' of undefined
And, when I use gatsby-source-graphql, I have this in gatsby-config.js...
{
resolve: "gatsby-source-graphql",
options: {
// This type will contain remote schema Query type
typeName: "Authors",
// This is field under which it's accessible
fieldName: "authors",
// Url to query from
url: "http://localhost:3000/graphql",
},
},
...and I get his error in my console when I run gatsby develop...
Error: Cannot find module 'gatsby/graphql'
As you can see, I'm confused about how to connect the schemas between the front-end and the back-end here. Any help on this would be much appreciated!
I am having issues setting up my Angular project with .NET MVC 5.0. I am not sure what's wrong with the below code. When I run the application, unexpectedly to me, app shows the template set in app-component.ts and not login
const appRoutes: Routes = [
{ path: '', redirectTo: 'login', pathMatch:'full' },
{ path: 'login', component: LoginComponent },
// otherwise redirect to home
{ path: '**', redirectTo: 'login' }
];
To test out the things, and ignore MVC controller/view routing for a second, I also tried creating html file inside in my login folder,
#Component({
moduleId: module.id,
templateUrl: 'login-component.html' -- This was initially /Public/Login -Path to the MVC controller
})
Project is shared on a github project here
https://github.com/GAK-MPRO/AngularMVCStarter/tree/Master/A2Rnd
My question is.. what do I need to do to route my views using MVC routing with views rendered by calling controllers.
Change the order in which your routes are defined. The default routes should always be at the end of the route list:
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: 'login', pathMatch:'full' },
// otherwise redirect to home
{ path: '**', redirectTo: 'login', pathMatch:'full' }
];
I just looked at your code on git hub. The bootstrap module is trying to bootstrap appcomponent and the appcomponent does not have an router-outlet tag. Edit the template in the app.component.ts file to include
<router-outlet></router-outlet>
and it should show you both app component and login components html content.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1><br/><router-outlet></router-outlet>',
})
export class AppComponent { name = 'Angular'; }
I'm working on a Rails 5.0.6 as an API. I am also running a React application for the front end running on a node server version v9.8.0. On the React app which is running on localhost:3000 I get the following error:
The rails is used as an API so in the controllers I return #drinks in json format.
drinks_controller.rb
class DrinksController < ApiController
# GET /drinks
def index
#drinks = Drink.select("id,title").all
render json: #drinks.to_json
end
# GET /drinks/1
def show
#drink = Drink.find(params[:id])
render json: #drink.to_json(:include => { :ingredients => { :only => [:id, :description] }})
end
end
I run both servers locally using Procfile in Profile.dev
web: cd client && PORT=3000 npm start
api: PORT=3001 && bundle exec rails s
When I go to the rails server which is running on localhost:3001/api/drinks I get the following:
[{"id":1,"title":"Sparkling Negroni"},{"id":2,"title":"Pineapple-JalapeƱo Margarita"}]
which is in json format, On the app.js im fetching from that endpoint
class App extends Component {
componentDidMount() {
window.fetch('api/drinks')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error))
}
Is it the proxy not working?
{
"name": "package-json",
"version": "4.0.1",
"description": "Get metadata of a package from the npm registry",
"license": "MIT",
"repository": "sindresorhus/package-json",
"proxy": "http://localhost:3001",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus#gmail.com",
"url": "sindresorhus.com"
}
I can't understand what the issue is?
I suspect your rails app is returning html when fetch is expecting JSON... The < character is indicative that an HTML string is being delivered, (the JSON parser is choking on HTML).
Try dumping the response "as is" to see what you're receiving.
class App extends Component {
componentDidMount() {
window.fetch('api/drinks')
.then(response => {
console.log(response.status);
console.log(response.body);
return response.json();
})
.then(json => console.log(json))
.catch(error => console.log(error))
}
I have a simple Ember 2.4 application. Here's the relevant code
../models/invitation.js
import DS from 'ember-data';
export default DS.Model.extend({
email: DS.attr('string')
});
../controllers/index.js
import Ember from 'ember';
export default Ember.Controller.extend({
emailAddress: '',
actions: {
saveInvitation() {
const email = this.get('emailAddress');
const newInvitation = this.store.createRecord('invitation', {
email: email,
});
newInvitation.save();
}
}
});
When I trigger the saveInvitation action, my Rails backend does not receive any parameters. The right action/controller receives the request but the only parameters are {action: "create", controller: "invitations"}.
Am I missing something? Shouldn't the parameters include the invitation with the email?
It seems that the default Ember adapter sends a content type application/vdn.api+json which is not automatically registered by Rails and parse the JSON arguments.
A fix for this was to register the right mime types under rails config
api_mime_types = %W(
application/vnd.api+json
text/x-json
application/json
)
Mime::Type.unregister :json
Mime::Type.register 'application/json', :json, api_mime_types
See https://github.com/rails-api/active_model_serializers/issues/1027
add following to config/initializers/json_adapter.rb
ActiveSupport.on_load(:action_controller) do
require 'active_model_serializers/register_jsonapi_renderer'
end
This may helps