Angularjs Fileupload change upload URL? - angularjs

I use angular to upload the file as below :
If I run the following code, I get 403(Forbidden)
var contextRoot = "http://localhost\\:6060/nomunoli";
...
...
uploadFile : function(taglist, description, userid, file) {
return $upload.upload({
url : contextRoot + "/auth/insertNMNL001FUN02",
fields : {
'description' : description,
'userId' : userid,
'tagList' : taglist,
},
file : file,
fileFormDataName : 'file'
});
},
...
In debugger console
POST http://localhost/:6060/nomunoli/auth/insertNMNL001FUN02 403 (Forbidden)
b # angular.min.js:79
s # angular.min.js:74
c.$get.f # angular.min.js:71
l.promise.then.J # angular.min.js:101
(anonymous function) # angular.min.js:102
a.$get.h.$eval # angular.min.js:113
a.$get.h.$digest # angular.min.js:110
a.$get.h.$apply # angular.min.js:113
(anonymous function) # angular.min.js:195
n.event.dispatch # jquery-2.1.3.min.js:3
n.event.add.r.handle # jquery-2.1.3.min.js:3
When I change the code as below, it is OK.
...
uploadFile : function(taglist, description, userid, file) {
return $upload.upload({
url : "http://localhost\\:6060/nomunoli/auth/insertNMNL001FUN02",
fields : {
'description' : description,
'userId' : userid,
'tagList' : taglist,
},
file : file,
fileFormDataName : 'file'
});
},
...

Related

wkhtmltopdf reported an error: Exit with code 1 due to network error: ContentNotFoundError

good day, please im having this error when i click Export to pdf button…………………
‘’’
views.py
#login_required(login_url='loginpage')
#cache_control(no_cache=True, must_rev alidate=True, no_store=True)
def exportToPdf(request, pk):
c = get_object_or_404(candidate, id=pk)
cookies = request.COOKIES
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'cookie' : [
('csrftoken', cookies ['csrftoken']),
('sessionid', cookies ['sessionid'])
]
}
pdf = pdfkit.from_url('http://127.0.0.1:8000/'+str(c.id), False, options = options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-disposition'] = 'attachment; filename=candidate.pdf'
return response
urls.py
path('int:pk/exporttopdf/', views.exportToPdf, name='exporttopdf'),
‘’’

How do I make two functions of a function based views communicate with each other in django?

I am new to Django and working on a project. I have to communicate two functions of views in Django.
views.py
#login_required
def likepost(request,id):
post = NewPost.objects.get(id = id)
is_like = False
for like in post.likepost.all():
if like == request.user and request.method == "POST":
is_like = True
break
if not is_like:
post.likepost.add(request.user)
else:
post.likepost.remove(request.user)
return JsonResponse({
"is_like" : is_like,
})
This is my likepage function which I want to call in my index function. The index function has been given below.
def index(request):
posts = NewPost.objects.all().order_by("-timestamp")
page = Paginator(posts,3)
page_req = request.GET.get('page')
page_view = page.get_page(page_req)
num = "a" * page_view.paginator.num_pages
is_like = likepost(posts.id)
if request.user.is_authenticated:
if request.method == "POST":
post = NewPostForm(request.POST)
user = request.user
timestamp = datetime.now()
if post.is_valid:
post = post.save(commit=False)
postdata = NewPost(post=post,user=user,timestamp=timestamp)
postdata.save()
# return Response({"message" : "Post created successfully 😊!"})
return render(request,"network/index.html",{
"post" : post,
# "user" : user,
# "posts" : posts,
"timestamp" : timestamp,
"page_view" : page_view,
"num" : num,
"is_like" : is_like,
})
# JsonResponse(posts, safe=False)
else:
post = NewPostForm()
return render(request,"network/index.html",{
"post" : post,
"posts" : posts,
"page_view" : page_view,
"num" : num,
"is_like" : is_like,
})
return render(request,"network/index.html",{
"posts" : posts,
"page_view" : page_view,
"num" : num,
"is_like" : is_like,
})
Although I have id attribute in my model, it gives the following error.
How can I fix it? I want to make a like button.
To fix the issue you just add user to is_like = likepost(posts.user.id).I think you need to query post by the user id not just the posts.id,so hopefully it should work now.
def index(request):
posts = NewPost.objects.all().order_by("-timestamp")
page = Paginator(posts,3)
page_req = request.GET.get('page')
page_view = page.get_page(page_req)
num = "a" * page_view.paginator.num_pages
is_like = likepost(posts.user.id)
if request.user.is_authenticated:
if request.method == "POST":
post = NewPostForm(request.POST)
user = request.user
timestamp = datetime.now()
if post.is_valid:
post = post.save(commit=False)
postdata = NewPost(post=post,user=user,timestamp=timestamp)
postdata.save()
# return Response({"message" : "Post created successfully 😊!"})
return render(request,"network/index.html",{
"post" : post,
# "user" : user,
# "posts" : posts,
"timestamp" : timestamp,
"page_view" : page_view,
"num" : num,
"is_like" : is_like,
})
# JsonResponse(posts, safe=False)
else:
post = NewPostForm()
return render(request,"network/index.html",{
"post" : post,
"posts" : posts,
"page_view" : page_view,
"num" : num,
"is_like" : is_like,
})
return render(request,"network/index.html",{
"posts" : posts,
"page_view" : page_view,
"num" : num,
"is_like" : is_like,
})

i see "405: Method Not Allowed" when trying following code on Python 3.8.3

https://tutorialedge.net/python/create-rest-api-python-aiohttp/
from aiohttp import web
import json
async def handle(request):
response_obj = { 'status' : 'success' }
return web.Response(text=json.dumps(response_obj))
async def new_user(request):
try:
print("AT Epoint" )
## happy path where name is set
user = request.query['name']
## Process our new user
print("Creating new user with name: " , user)
response_obj = { 'status' : 'success' }
## return a success json response with status code 200 i.e. 'OK'
return web.Response(text=json.dumps(response_obj), status=200)
except Exception as e:
print("AT EXCEPTION" )
## Bad path where name is not set
response_obj = { 'status' : 'failed', 'reason': str(e) }
## return failed with a status code of 500 i.e. 'Server Error'
return web.Response(text=json.dumps(response_obj), status=500)
Once you have implemented the listener function, register it with the aiohttp instance.
app.router.add_post('/user', new_user)
Source: TutorialEdge

Send a POST request from React Component to Spring Boot Controller

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!

How to resolve access control in Rails?

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) {

Resources