So I have a React component called UpdateJobComponent. From here the user can either update a job or create a job (depending on the button they clicked in the previous component). The update of a job works fine however when I try to create a job i get the following errors:
Errors
Put http://localhost:8080/jobs/-1 500
Uncaught (in promise) Error: Request failed with status code 500
at createError
It tells me it's a PUT request and not a POST. However I thought I have it said up properly to match the the createJob PostMapping Controller. Below is the UpdateJobComponent code as well as the service files and also the Controller as well as the JobDataService.
I'm quite sure that the updateJob method in my JobController is receiving the POST and that's why I'm getting the problem but I can't figure out how to make the createJob in the JobController get it.
If you want to see anymore code just let me know, I tried to trim it as much as possible so not to take too long to look over! I'd really appreciate any help you can offer!
UpdateJobComponent
// imports
class UpdateJobComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
employer: this.props.match.employer,
description: ''
}
// bind methods
}
componentDidMount() {
if (this.state.id == -1) {
console.log("Not mounting")
return;
}
console.log(this.state.id)
console.log("mounting")
let userName = AuthenticationService.getLoggedUser()
JobDataService.retrieveJob(userName, this.state.id)
.then(response => this.setState({
description: response.data.description,
employer: response.data.employer,
jobTitle: response.data.jobTitle
}))
}
// Error handling for form
validate(values) {
let errors = {} // add validation for every field!!!!!!
if (!values.description) {
errors.description = 'Enter a description'
} else if (values.description.length < 5) {
errors.description = 'Description must be at least 5 characters long'
}
return errors
}
// When save is clicked
onSubmit(values) {
// let employer = this.state.employer
// let id = this.state.id
// let jobTitle = this.state.jobTitle
let job = {
id: this.state.id,
employer: values.employer,
jobTitle: values.jobTitle,
description: values.description
}
if (this.state.id === -1) {
JobDataService.createJob(job)
.then(() => this.props.history.push('/jobs'))
} else {
JobDataService.updateJob(job.jobTitle, job.employer, this.state.id, job)
.then(() => this.props.history.push('/jobs'))
}
}
render() {
let { description, employer, jobTitle } = this.state
return (
<div>
<h3>Update {this.state.employer}'s {this.state.jobTitle} Job</h3>
<div className="container">
<Formik
initialValues={{description: description, employer: employer, jobTitle: jobTitle}}
onSubmit={this.onSubmit}
validateOnChange={false}
validateOnBlur={false}
validate={this.validate}
enableReinitialize={true}
>
{
(props) => (
<Form>
// Formik form, removed to make post smaller...
<div className="btn-group mr-2" role="group" aria-label="First group">
<button className="btn btn-success" type="submit">Save</button>
</div>
JobDataService
// imports
const API_URL = 'http://localhost:8080'
const GET_ALL_JOBS_URL = `${API_URL}/jobs/`
updateJob(jobTitle, employer, id, job) {
return axios.put(`${GET_ALL_JOBS_URL}${id}`, job);
}
createJob(job) {
return axios.post(`${GET_ALL_JOBS_URL}`, job);
}
JobController
#Autowired
private JobService jobService;
#PostMapping("/jobs/")
public ResponseEntity<Job> createJob(#RequestBody Job job) {
Job createdJob = jobService.createJob(job);
java.net.URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(createdJob.getId())
.toUri();
return ResponseEntity.created(uri).build();
}
#PutMapping("/jobs/{id}")
public ResponseEntity<Job> updateJob(#PathVariable long id, #RequestBody Job job) {
job.setId(id);
return ResponseEntity.ok().body(this.jobService.updateJob(job));
}
// Other get and delete methods
JobService
public Job createJob(Job job) {
if(job.getId() == -1 || job.getId() == 0) {
job.setId(++idCounter);
jobRepository.insert(job);
}
return jobRepository.save(job);
}
public Job updateJob(Job job) {
Optional < Job > jobDb = this.jobRepository.findById(job.getId());
if (jobDb.isPresent()) {
Job jobUpdate = jobDb.get();
jobUpdate.setId(job.getId());
jobUpdate.setEmployer(job.getEmployer());
jobUpdate.setJobTitle(job.getJobTitle());
jobUpdate.setDescription(job.getDescription());
jobRepository.save(jobUpdate);
return jobUpdate;
} else {
throw new ResourceNotFoundException("Record not found with id : " + job.getId());
}
}
// Other methods
Edit
Full error message:
PUT http://localhost:8080/jobs/-1 500
dispatchXhrRequest # 1.chunk.js:561
xhrAdapter # 1.chunk.js:411
dispatchRequest # 1.chunk.js:994
Promise.then (async)
request # 1.chunk.js:807
Axios.<computed> # 1.chunk.js:831
wrap # 1.chunk.js:1308
updateJob # main.chunk.js:1428
onSubmit # main.chunk.js:955
(anonymous) # 1.chunk.js:4699
(anonymous) # 1.chunk.js:5014
(anonymous) # 1.chunk.js:4709
Promise.then (async)
(anonymous) # 1.chunk.js:4705
(anonymous) # 1.chunk.js:5014
(anonymous) # 1.chunk.js:4750
(anonymous) # 1.chunk.js:5014
callCallback # 1.chunk.js:16321
invokeGuardedCallbackDev # 1.chunk.js:16370
invokeGuardedCallback # 1.chunk.js:16423
invokeGuardedCallbackAndCatchFirstError # 1.chunk.js:16438
executeDispatch # 1.chunk.js:16569
executeDispatchesInOrder # 1.chunk.js:16594
executeDispatchesAndRelease # 1.chunk.js:16697
executeDispatchesAndReleaseTopLevel # 1.chunk.js:16706
forEachAccumulated # 1.chunk.js:16678
runEventsInBatch # 1.chunk.js:16723
runExtractedPluginEventsInBatch # 1.chunk.js:16865
handleTopLevel # 1.chunk.js:21818
batchedEventUpdates$1 # 1.chunk.js:40326
batchedEventUpdates # 1.chunk.js:17401
dispatchEventForPluginEventSystem # 1.chunk.js:21914
attemptToDispatchEvent # 1.chunk.js:22031
dispatchEvent # 1.chunk.js:21934
unstable_runWithPriority # 1.chunk.js:51411
runWithPriority$2 # 1.chunk.js:28193
discreteUpdates$1 # 1.chunk.js:40343
discreteUpdates # 1.chunk.js:17426
dispatchDiscreteEvent # 1.chunk.js:21901
I just added an if statement in the updateJob method to check if the id was -1. It's far from pretty and will need to be fixed again but wll do for now. Thanks for your time Code-Apprentice!
Related
I am trying to send image from react to django rest framework,this is what I tried so far,it gives Unsupported media type error, I am not sure if the problem is in the backend or frontend part. What else should I do in order to make it work?
backend
views.py
class ImageView(APIView):
permission_classes=[permissions.IsAuthenticated]
parser_classes=[MultiPartParser,FormParser]
def post(self,request,format=None):
print(request.data)
serializer=ImageSerializer(data=request.data)
if serializer.is_valid():
serializer.save();
return Response(status=200)
serializer.py
class ImageSerializer(serializers.ModelSerializer) :
class Meta:
model=Images;
fields=['image']
models.py
def upload_to(instance,filename):
return 'images/{filename}'.format(filename=filename)
class Images(models.Model):
image=models.ImageField(upload_to=upload_to)
settings.py
MEDIA_ROOT=BASE_DIR.joinpath('media')
MEDIA_URL='/media/'
frontend
Send_file.js
const Send_file=()=>{
const send_data=(e)=>{
e.preventDefault();
let data={
'image':e.target[0].files[0]
}
axios.post(`${BASE_URL}/upload_image/`,data,config)
}
return <>
<form enctype='multipart/form-data' onSubmit = {send_data}>
<input type='file'/>
<button type='submit'>SEND FILE</button>
</form>
</>
}
I think you need to set FileField in the ImageSerializer.
class ImageSerializer(serializers.ModelSerializer):
upload_image = serializers.FileField(max_length = 10000000, allow_empty_file = False, use_url = False, write_only = True)
class Meta:
model = Images
fields = ('upload_image', 'image')
def create(self, validated_data):
image_source = validated_data.pop('upload_image')
new_image = Images.objects.create(image = image_source)
return new_image
And please change the image key in the data object in Send_file.js into upload_image.
const Send_file=()=>{
const send_data=(e)=>{
e.preventDefault();
let data={
'upload_image':e.target[0].files[0] # here
}
axios.post(`${BASE_URL}/upload_image/`,data,config)
}
...
}
I have created a database using PostgreSQL. I have used LEFT JOIN to join a comments table to a reviews table. The frontend is created using React. I can only delete a review if it has 0 comments, if there are any comments on the review when I try to delete it a 500 internal server error throws. I was sure the LEFT JOIN would delete a review with or without comments, so not sure why this isn't working?
Any suggestions are appreciated, thank you.
https://nc-games-kirsty-richmond.netlify.app
// seed.js file
// Create Reviews Table //
const seed = async (data) => {
const { categoryData, commentData, reviewData, userData } = data;
await db.query(`DROP TABLE IF EXISTS comments, reviews, users, categories;`);
await db.query(`
CREATE TABLE reviews (
review_id SERIAL PRIMARY KEY,
title VARCHAR(75) NOT NULL,
designer VARCHAR(55) NOT NULL,
owner VARCHAR(180) REFERENCES users(username),
review_img_url VARCHAR(500) DEFAULT
'https://images.pexels.com/photos/163064/play-stone-network-networked-interactive-163064.jpeg',
review_body VARCHAR(1000) NOT NULL,
category VARCHAR(75) REFERENCES categories(slug),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
votes INT DEFAULT 0
);
`);
// Create Comments Table //
await db.query(`
CREATE TABLE comments (
comment_id SERIAL PRIMARY KEY,
body VARCHAR(1000) NOT NULL,
votes INT DEFAULT 0,
author VARCHAR(75) REFERENCES users(username) NOT NULL,
review_id INT REFERENCES reviews(review_id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
// review-models.js
exports.selectReviewById = async (review_id) => {
const review = await db.query(
`SELECT reviews.*, COUNT(comment_id)
AS comment_count
FROM reviews
LEFT JOIN comments
ON comments.review_id = reviews.review_id
WHERE reviews.review_id = $1
GROUP BY reviews.review_id;`,
[review_id]
);
return review.rows[0];
};
exports.removeReview = async (review_id) => {
removeComment();
const review = await db.query(
`DELETE FROM reviews
WHERE review_id = $1;`,
[review_id]
);
return review.rows[0];
};
Errors in console:
DELETE http://be-nc-games-app.herokuapp.com/api/reviews/114 500 (Internal Server Error)
dispatchXhrRequest # xhr.js:210
xhrAdapter # xhr.js:15
dispatchRequest # dispatchRequest.js:58
request # Axios.js:112
Axios.<computed> # Axios.js:136
wrap # bind.js:9
deleteReview # api.js:116
handleDelete # ReviewCard.jsx:55
onClick # ReviewCard.jsx:77
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4070
executeDispatch # react-dom.development.js:8243
processDispatchQueueItemsInOrder # react-dom.development.js:8275
processDispatchQueue # react-dom.development.js:8288
dispatchEventsForPlugins # react-dom.development.js:8299
(anonymous) # react-dom.development.js:8508
batchedEventUpdates$1 # react-dom.development.js:22396
batchedEventUpdates # react-dom.development.js:3745
dispatchEventForPluginEventSystem # react-dom.development.js:8507
attemptToDispatchEvent # react-dom.development.js:6005
dispatchEvent # react-dom.development.js:5924
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
discreteUpdates$1 # react-dom.development.js:22413
discreteUpdates # react-dom.development.js:3756
dispatchDiscreteEvent # react-dom.development.js:5889
Uncaught (in promise) Error: Request failed with status code 500
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)
createError # createError.js:16
settle # settle.js:17
onloadend # xhr.js:66
Promise.then (async)
handleDelete # ReviewCard.jsx:55
onClick # ReviewCard.jsx:77
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4070
executeDispatch # react-dom.development.js:8243
processDispatchQueueItemsInOrder # react-dom.development.js:8275
processDispatchQueue # react-dom.development.js:8288
dispatchEventsForPlugins # react-dom.development.js:8299
(anonymous) # react-dom.development.js:8508
batchedEventUpdates$1 # react-dom.development.js:22396
batchedEventUpdates # react-dom.development.js:3745
dispatchEventForPluginEventSystem # react-dom.development.js:8507
attemptToDispatchEvent # react-dom.development.js:6005
dispatchEvent # react-dom.development.js:5924
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
discreteUpdates$1 # react-dom.development.js:22413
discreteUpdates # react-dom.development.js:3756
dispatchDiscreteEvent # react-dom.development.js:5889
If you can delete only records that are not commented.
delete from reviews where id in (
select a.id
from reviews rv
left join comments cm on rv.id = cm.rev_id
where cm.id is null
)
Left join will be select all records. But if reviews are not commented these records showed as NULL. So adding the CM.ID IS NULL condition will filter only no comments records. After then using the subquery we can delete needed records.
I'm pretty new to React Hooks and I'm trying to figure out how to use react-firebase-hooks with custom claims.
My firebase Realtime Database is structured like so :
groups
--- key1
------- clients
------- info
--- key2
------- clients
------- info
Each user has a custom claim named "group" carrying the group Key.
I have this code so far but it's throwing me a:
Uncaught TypeError: Cannot read property 'hasCancelCallback' of undefined
at ChildEventRegistration.createCancelEvent"
function ClientList() {
const [firebaseUser, loadingFirebaseUser] = useAuthState(auth);
const [userGroup, setUserGroup] = useState();
useEffect(() => {
const fetchClaims = async () => {
const {
claims: { group },
} = await firebaseUser.getIdTokenResult();
setUserGroup(group);
};
if (firebaseUser) fetchClaims();
}, [firebase.database(), firebaseUser]);
const [snapshots, loading, error] = useList(
firebase.database().ref(`groups/${userGroup}/clients`)
);
return (
<div>
<h2>List of Clients</h2>
{userGroup && <p>{userGroup}</p>}
{error && <strong>Error: {error}</strong>}
{loading && <span>List: Loading...</span>}
{!loading && snapshots && (
<ul>
{snapshots.map((v) => (
<li key={v.key}>
{v.key}}
</li>
))}
</ul>
)}
</div>
);
}
I might be missing something very obvious here.
Here's a full stack trace of the error :
overrideMethod # react_devtools_backend.js:2557
printWarnings # vendors~main.chunk.js:36207
handleWarnings # vendors~main.chunk.js:36212
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage # vendors~main.chunk.js:36277
vendors~main.chunk.js:28144 Uncaught TypeError: Cannot read property 'hasCancelCallback' of undefined
at ChildEventRegistration.createCancelEvent (vendors~main.chunk.js:28144)
at vendors~main.chunk.js:23797
at Array.forEach (<anonymous>)
at viewRemoveEventRegistration (vendors~main.chunk.js:23796)
at syncPointRemoveEventRegistration (vendors~main.chunk.js:24047)
at syncTreeRemoveEventRegistration (vendors~main.chunk.js:24417)
at onComplete (vendors~main.chunk.js:24743)
at Object.onComplete (vendors~main.chunk.js:25874)
at vendors~main.chunk.js:16786
at PersistentConnection.onDataMessage_ (vendors~main.chunk.js:17069)
at Connection.onDataMessage_ (vendors~main.chunk.js:15624)
at Connection.onPrimaryMessageReceived_ (vendors~main.chunk.js:15617)
at WebSocketConnection.onMessage (vendors~main.chunk.js:15497)
at WebSocketConnection.appendFrame_ (vendors~main.chunk.js:15050)
at WebSocketConnection.handleIncomingFrame (vendors~main.chunk.js:15108)
at WebSocket.mySock.onmessage (vendors~main.chunk.js:14984)
ChildEventRegistration.createCancelEvent # vendors~main.chunk.js:28144
(anonymous) # vendors~main.chunk.js:23797
viewRemoveEventRegistration # vendors~main.chunk.js:23796
syncPointRemoveEventRegistration # vendors~main.chunk.js:24047
syncTreeRemoveEventRegistration # vendors~main.chunk.js:24417
onComplete # vendors~main.chunk.js:24743
(anonymous) # vendors~main.chunk.js:25874
(anonymous) # vendors~main.chunk.js:16786
PersistentConnection.onDataMessage_ # vendors~main.chunk.js:17069
Connection.onDataMessage_ # vendors~main.chunk.js:15624
Connection.onPrimaryMessageReceived_ # vendors~main.chunk.js:15617
(anonymous) # vendors~main.chunk.js:15497
WebSocketConnection.appendFrame_ # vendors~main.chunk.js:15050
WebSocketConnection.handleIncomingFrame # vendors~main.chunk.js:15108
mySock.onmessage # vendors~main.chunk.js:14984
I am trying to integrate a react app with go-ethereum using web3js.
an event Onsubmit will do the following:
1. Create an account.
2. Open the account.
3. Approve a smart contract with the created account.
Here is my code
import React, { Component } from 'react';
import './App.css';
import web3 from './web3';
....
class App extends Component {
constructor(props){
super(props);
this.state = {requester : '', receiver:'', balance: '', message:''};
}
async componentDidMount(){
const requester = await auth.methods.requester().call();
const receiver = await auth.methods.receiver().call();
const approvers = await auth.methods.approvers(0).call();
const balance = await web3.eth.getBalance(auth.options.address);
this.setState({requester,receiver,balance});
}
onSubmit = async (event)=>{
event.preventDefault();
console.log('Approving the smart contract ..... Mining in process ! ');
var pass = "xxxxxxx"
var newaccount = web3.eth.personal.newAccount(pass);
var promise1 = Promise.resolve(newaccount);
promise1.then(function(value) {
var accountnumber = value;
console.log(accountnumber);
web3.eth.personal.unlockAccount(accountnumber,pass, 1500);
auth.methods.approve().send({gas: '1000000',from: accountnumber});
console.log('Smart Contract approved ! ');
});
};
The account is getting created but while doing the transaction I am receiving the following error.
Approving the smart contract ..... Mining in process ! App.js:57
0x98f76b2673d545F55c0ff1e961f15EF0a7DfBaD3
App.js:71 Smart Contract
approved ! errors.js:29 Uncaught (in promise) Error: Returned error:
authentication needed: password or unlock
at Object.ErrorResponse (errors.js:29)
at index.js:125
at XMLHttpRequest.request.onreadystatechange (index.js:103)
at XMLHttpRequestEventTarget.dispatchEvent (xml-http-request-event-target.js:50)
at XMLHttpRequest._setReadyState (xml-http-request.js:288)
at XMLHttpRequest._onHttpResponseEnd (xml-http-request.js:459)
at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.
(xml-http-request.js:413)
at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.emit
(events.js:139)
at endReadableNT (_stream_readable.js:1030)
at afterTickTwo (index.js:31)
at Item.push../node_modules/process/browser.js.Item.run (browser.js:167)
at drainQueue (browser.js:131) ErrorResponse # errors.js:29 (anonymous) # index.js:125 request.onreadystatechange # index.js:103
XMLHttpRequestEventTarget.dispatchEvent #
xml-http-request-event-target.js:50 XMLHttpRequest._setReadyState #
xml-http-request.js:288 XMLHttpRequest._onHttpResponseEnd #
xml-http-request.js:459 (anonymous) # xml-http-request.js:413 emit #
events.js:139 endReadableNT # _stream_readable.js:1030 afterTickTwo #
index.js:31 push../node_modules/process/browser.js.Item.run #
browser.js:167 drainQueue # browser.js:131 setTimeout (async)
_fireError # index.js:72 sendTxCallback # index.js:465 (anonymous) # index.js:125 request.onreadystatechange # index.js:103
XMLHttpRequestEventTarget.dispatchEvent #
xml-http-request-event-target.js:50 XMLHttpRequest._setReadyState #
xml-http-request.js:288 XMLHttpRequest._onHttpResponseEnd #
xml-http-request.js:459 (anonymous) # xml-http-request.js:413 emit #
events.js:139 endReadableNT # _stream_readable.js:1030 afterTickTwo #
index.js:31 push../node_modules/process/browser.js.Item.run #
browser.js:167 drainQueue # browser.js:131 setTimeout (async)
runTimeout # browser.js:43
push../node_modules/process/browser.js.process.nextTick #
browser.js:156 nextTick # index.js:30 maybeReadMore #
_stream_readable.js:521 addChunk # _stream_readable.js:300 readableAddChunk # _stream_readable.js:278
push../node_modules/readable-stream/lib/_stream_readable.js.Readable.push
# _stream_readable.js:242 (anonymous) # response.js:47 write #
response.js:44
Edit: Changed the code to catch the errors
web3.eth.personal.unlockAccount(accountnumber,pass, 1500, function(err, result){
if(err){
alert("Error"+ err);
return;}
alert("Account Opening: "+ result);});
.....
auth.methods.approve().send({gas: '1000000',from: accountnumber}, function(err, result){
if(err){
alert("Error"+ err);
return;}
alert("Account address: "+ result);
console.log('Smart Contract approved ! ');});
The web3.eth.personal.unlockAccount is returning "true" but the still the auth.methods.approve is giving me the error.
So, after some major changes to the code, I am able to do the following from an onSubmit event on a react app.
Create an account.
Transfer some gas to it.
Unlock the account.
Sign a contract with the account.
Here is the code
onSubmit = async (event)=>{
event.preventDefault();
console.log('Approving the smart contract ..... Mining in process ! ');
var pass = "passsword1"
var newaccount = web3.eth.personal.newAccount(pass);
var promise1 = Promise.resolve(newaccount);
promise1.then(function(value) {
var accountnumber = value;
console.log(accountnumber);
web3.eth.personal.unlockAccount('0x197022acd263e8be0f6b65b10d1e5cdbaa244c17',"*****", 1500, function(err, result){
if(err){
alert("Error"+ err);
return;
}else {
alert("Parent Opening: "+ result);
web3.eth.sendTransaction({
from: "0x197022acd263e8be0f6b65b10d1e5cdbaa244c17",
to: accountnumber,
value: '100000000000000000',
}, function(err, transactionHash) {
if (err) {
console.log(err);
} else {
web3.eth.personal.unlockAccount(accountnumber,pass, 1500, function(err, result){
if(err){
alert("Error"+ err);
return;
}else{
console.log(web3.eth.getBalance(accountnumber));
alert("Child Opening: "+ result);
auth.methods.approve().send({gas: '20000000',from: accountnumber}, function(err, result){
if(err){
alert("Error"+ err);
return;
}else{
console.log("Account address: "+ result);
console.log('Smart Contract approved ! ');
}
});
}
});
}
});
}
});
};
I am trying to send a post request to my rails api using angular js post request but I am getting this error :
XMLHttpRequest cannot load http://localhost:3000/api/v1/dis_generics. 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:9000' is therefore not allowed access. The response had HTTP status code 404.
I am trying to find a way how to send a post request using angular to rails api . My controller in rails is like this :
class DisGenericsController < ApplicationController
before_action :set_dis_generic, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token
# GET /dis_generics
# GET /dis_generics.json
def index
# #dis_generics = DisGeneric.all
respond_to do |format|
format.html
format.json { render json: DisGenericDatatable.new(view_context) }
end
end
# GET /dis_generics/1
# GET /dis_generics/1.json
def show
end
# GET /dis_generics/new
def new
#dis_generic = DisGeneric.new
end
# GET /dis_generics/1/edit
def edit
end
# POST /dis_generics
# POST /dis_generics.json
def create
#dis_generic = DisGeneric.new(dis_generic_params)
respond_to do |format|
if #dis_generic.save
format.html { redirect_to #dis_generic, notice: 'Dis generic was successfully created.' }
format.json { render :show, status: :created, location: #dis_generic }
else
format.html { render :new }
format.json { render json: #dis_generic.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /dis_generics/1
# PATCH/PUT /dis_generics/1.json
def update
respond_to do |format|
if #dis_generic.update(dis_generic_params)
format.html { redirect_to #dis_generic, notice: 'Dis generic was successfully updated.' }
format.json { render :show, status: :ok, location: #dis_generic }
else
format.html { render :edit }
format.json { render json: #dis_generic.errors, status: :unprocessable_entity }
end
end
end
# DELETE /dis_generics/1
# DELETE /dis_generics/1.json
def destroy
#dis_generic.destroy
respond_to do |format|
format.html { redirect_to dis_generics_url, notice: 'Dis generic was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_dis_generic
#dis_generic = DisGeneric.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def dis_generic_params
params.require(:dis_generic).permit(:name, :is_combination, :rxcui, :status_id, :food_id, :hepatic_id, :renal_imp_id, :release_status_id, :is_essential)
end
end
and this is my angular request :
var req = {
method: 'POST',
url: 'http://localhost:3000/api/v1/dis_generics',
headers: {
"Content-Type": "application/json"
},
data: {}
}
$http(req).success(function(data, status, header, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
This is my application controller :
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
include StaticPagesHelper
skip_before_filter :verify_authenticity_token
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
protect_from_forgery unless: -> { request.format.json? }
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = "1728000"
end
# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.
def cors_preflight_check
if request.method == :options
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
end
You need to add access-control header in your rails app OR you can just change the method to 'JSONP' as per this thread: AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource
var req = {
method: 'JSONP',
url: 'http://localhost:3000/api/v1/dis_generics',
headers: {
"Content-Type": "application/json"
},
data: {}
}
$http(req).success(function(data, status, header, config) {