I have a Rails sever and I'm trying to make a fetch request from a React client. I want to get the comments of a post every time a new comment is made.
posts_controller.rb
# GET /post/1
# GET /post/1.json
def show
#post = Post.kept.friendly.find(params[:id])
#comments = #post.comments.kept.order(created_at: :desc)
end
My React component
useEffect(() => {
fetch('/posts/post-title')
.then((res) => {
console.log("res", res);
})
.catch((err) => {
console.log("err", err);
});
}, []);
Result
res Response {type: "basic", url: "http://localhost:3000/posts/post-title", redirected: false, status: 200, ok: true, …}
I open that Response but I don't see any comments json. I have tried doing res.json() but I get undefined.
What I'm doing wrong?
change your show action to this
def show
#post = Post.kept.friendly.find(params[:id])
#comments = #post.comments.kept.order(created_at: :desc)
render json: #comments
end
and your JS to this
useEffect(() => {
fetch('/posts/post-title')
.then(res => res.json())
.then((post) => {
console.log(post)
})
.catch((err) => {
console.log("err", err);
});
}, []);
Related
I am building a react-native app with rails api. I have a players_controller with create, index, update actions. I can do all things(create, index, update) from postman. But when I tried form fetch request from react action. I could only index and create player model. On update I get this error in debugger console.
:3000/players/1:1 OPTIONS http://localhost:3000/players/1
XMLHttpRequest cannot load http://localhost:3000/players/1. Response
for preflight has invalid HTTP status code 404
in Rails my players_controller.rb
class PlayersController < ApplicationController
skip_before_action :verify_authenticity_token
respond_to :json
def index
#players = Player.find_by(player_id: params[:player_id])
player = Player.all
render json: #players
end
def create
player = Player.new(player_params)
if player.save
render json: player, status: 201
else
render json: { errors: player.errors }, status: 422
end
end
def update
player = Player.find(params[:id])
player.update(player_params)
if player.save
render json: player, status: 201
else
render json: { errors: player.errors }, status: 422
end
end
private
def player_params
params.require(:player).permit(:username, :profile_pic, :player_id)
end
end
In my react-native app I have action
export const profilePicUpdate = (player, profile) => (dispatch) => {
const obj = player;
obj.profile_pic = profile;
fetch(`http://localhost:3000/players/${player.id}`, {
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
obj
})
}).then(() => {
dispatch({
type: 'PROFILE_PIC_UPDATE',
payload: profile
});
NavigatorService.navigate('Profile');
}).catch((error) => {
console.log('Error', error);
});
};
It is need to see your roues.rb file, but also maybe you need to add
gem 'rack-cors'
and set up it
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
in config/initializers/cors.rb
I need to upload an image of my user from my react app to Rails api only server.
My HTML input file
<input ref={(input) => this.profileImage_input = input}
type="file"
name="user-profile-image"
className="small-font-size"
onChange={(e) => this.handleChange(e)}/>
So this is my component upload function.
let profileUploadImage = this.profileImage_input.files;
let user_info = {};
user_info = {
username: this.username_input.value,
profile_image: profileUploadImage
};
this.props.update_user_with_image_server(user_info,this.props.user.user.id)
My actionCreator
export function update_user_with_image_server(user_info,user_id){
let formData = new FormData();
for(let key in user_info) {
if(user_info.hasOwnProperty(key)) {
formData.append(key, user_info[key]);
}
}
return function (dispatch) {
fetch(deafaultUrl + '/v1/users_profile/' + user_id,
{
headers: {
'Content-Type': 'multipart/form-data'
},
method: "PATCH",
body: formData
})
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(json){
});
}
}
My rails user controller
def update_with_image
user = current_user
if user.update_attributes(user_update_params)
# Handle a successful update.
render json: user, status: 200
else
render json: { errors: user.errors }, status: 422
end
end
private
def user_update_params
params.permit(:username,:profile_image)
end
So the problem is it seems like user_update_params didn't workout rails cannot read the data and update in correctly so how could i fix this?
Thanks!
I want send data from angularjs to rails server. For this, I have an angularjs service that I use GET,POST,DELETE,UPDATE method. I can use GET method, but for other method I cannot use, beacause I have to sent parameter to server, but I cannot do this.
record.js:
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records', function($scope, Session, Records){
$scope.records = Records.index();
}]);
recordService.js:
'use strict';
var app = angular.module('recordService', ['ngResource']);
//angular.module('recordService', ['ngResource'])
app.factory('Records', function($resource) {
return $resource('/api/record.json', {}, {
index: { method: 'GET', isArray: true},
create: { method: 'POST' }
});
})
.factory('Secure', function($resource){
return $resource('/api/record/:record_id.json', {}, {
show: { method: 'GET' },
update: { method: 'PUT' },
destroy: { method: 'DELETE' }
});
});
and I get data in rails server by below code:
class Api::V1::RecordController < Api::V1::BaseController
def index
respond_with(Record.all)
end
def show
#data = Record.find(params[:id]).to_json()
respond_with(#data)
end
def update
#data = Record.find(params[:id])
respond_to do |format|
if #data.update_attributes(record_params)
format.json { head :no_content }
else
format.json { render json: #data.errors, status: :unprocessable_entity }
end
end
end
def create
#data = Record.create(record_params)
#data.save
respond_with(#data)
end
def destroy
#data = Record.find(params[:id])
#data.destroy
respond_to do |format|
format.json { head :ok }
end
end
private
def record_params
params.require(:record).permit(:name)
end
end
I don't know how can I send method from angularjs controller to rails server. I try below code, but I don't successful:
Records.create(function() {
//"name" is the name of record column.
return {name: test3};
});
but I get below error in rails server:
Started POST "/api/record.json" for 127.0.0.1 at 2014-08-30 17:55:27 +0430
Processing by Api::V1::RecordController#create as JSON
How can I fix this problem? How can I send parameter to rails server?
I want send delete method to rails server. I know I have to send record.id to server, I use below type:
//type 1
var maskhare = { record_id: 4};
Secure.destroy(function(){
return maskhare.json;
});
//type 2
Secure.destroy(4);
but I get below error in server:
Started DELETE "/api/record" for 127.0.0.1 at 2014-08-30 19:01:21 +0430
ActionController::RoutingError (No route matches [DELETE] "/api/record"):
I fix correct url in recordService.js, but I don't know why request is send to before url again. Where is the problem?
It looks like you are successfully making a request, the last line there says that a POST request was made and went to the right controller and action.
The problem is strong parameters. You need to add name to the filtered parameters list.
private
def record_params
params.require(:record).permit(:secure, :name)
end
Also rails expects the parameters in the following format: { record: {name: 'something"} }
To fix your second problem
I would try to follow this recipe
Replace your code with this:
app.factory("Secure", function($resource) {
return $resource("/api/record/:id", { id: "#id" },
{
'show': { method: 'GET', isArray: false },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
}
);
});
and then
Secure.destroy({id: 4});
Keep in mind that if you add respond_to :json in your controller then you can omit the .json in the URLs. Like so:
class Api::V1::RecordController < Api::V1::BaseController
respond_to :json
...
end
I am making and ajax call to hit the controller but it is showing the 404 error:
My controller method is like:
def get_user_time
if(params[:user])
#user_time_checks = UserTimeCheck.where(:user_id => params[:user])
end
end
And my route for this is like:
post "user_time_checks/get_user_time"
And my ajax script is like:
function get_user_time(id) {
var user_id = id;
if(user_id != ''){
$.ajax({
url:"get_user_time?user="+user_id,
type:"POST",
success: function(time){
console.log(time);
},error: function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
}
});
}
}
Try this:
$.ajax({
url:"user_time_checks/get_user_time",
type:"POST",
data: {
user: user_id
},
success: function(time){
console.log(time);
},error: function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
}
});
Also make sure you really need to do POST method and that rails route does not require specific paramater like :user_id. Basically check the output from
rake routes | grep get_user_time
Your route should be:
post "user_time_checks/get_user_time" => "user_time_checks#get_user_time"
Also, since the purpose of the request is to get some data, you should make it a GET request instead. So:
function get_user_time(id) {
var user_id = id;
if(user_id != ''){
$.get("get_user_time",
{user: user_id})
.success(function(time) {
console.log(time);
})
.error(function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
});
}
}
Lastly, maybe you should tell the controller to be able to repond_to json:
def get_user_time
if(params[:user])
#user_time_checks = UserTimeCheck.where(:user_id => params[:user])
respond_to do |format|
format.html # The .html response
format.json { render :json => #user_time_checks }
end
end
end
In my ruby on rails code I want to send back json response to client. Since I am new to ruby on rails I do not know how can I do this. I want to send error = 1 and success = 0 as json data if data does not save to database and if it successfully saves that it should send success = 1 and error = 0 Please see my code below
here is my controller
class ContactsController < ApplicationController
respond_to :json, :html
def contacts
error = 0
success = 1
#contacts = Contact.new(params[:contact])
if #contacts.save
respond_to do |format|
format.json { render :json => #result.to_json }
end
else
render "new"
end
end
end
here is my javascript code
$('.signupbutton').click(function(e) {
e.preventDefault();
var data = $('#updatesBig').serialize();
var url = 'contacts';
console.log(data);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
There are tons of other elegant ways, but this is right:
class ContactsController < ApplicationController
def contacts
#contacts = Contact.new(params[:contact])
if #contacts.save
render :json => { :error => 0, :success => 1 }
else
render :json => { :error => 1, :success => 0 }
end
end
end
Add also a route to routes.rb. If you need to use html response you have to include respond_to do |format|.
You have to adjust your routes to accept json data
match 'yoururl' => "contacts#contacts", :format => :json
Then it will work