How to change http exception in adonisjs? - node.js

I am newbie in adonisjs.
I want to implement custom response if route method not match.
I have route like this
Route.post('/create', function * (request, response) {response.send('success')})
when call url /create with GET in browser, It send respond 404 not found. Can I use custom response with 405 method not allowed?

The Adonisjs not use request and response like expressjs, you need deconstruct the object.
Your route will running with that code:
Route.post('/create', ({ request, response }) => {
response.send('success')
})
or
Route.post('/create', (ctx) => {
ctx.response.send('success')
})

I just found out the simplest method.
Just put this at the bottom of all the routes
Route.get('*', ({ view }) => view.render('errorPage'))
It will check all the routes from the top, reaches the bottom and hits the view

Related

Unable to get data from React App to Node server

So Am unable to make a search function i want to get a variable from search field and show the results that matched but am constantly getting this error
variable undefined when i try to console.log it in the node server
Edit-- i have already changed the axios.post to axios.get
app.get(`/search/`, (req, res) => {
let {name} =req.body
var Desc = name
console.log(name)
var Op= Desc+'%'
const q = "SELECT * FROM taric where Description LIKE ? ";
con.query(q,[Op], (err, search) => {
if (err) {
console.log(err);
return res.json(err);
}
console.log(search);
return res.json(search);
});
});
As you can see you are making POST request from frontend where as there is no POST request route to handle your request. As you have make route of GET for fetching the data from backend you need to make GET request from frontend as well. So you need to do as below:
axios.get(`your_endpoint_route_goes_here`);
instead of this:
axios.post(`your_endpoint_route_goes_here`, requestBodyObj);
HTTP methods are not the same.
You are using app.get in the server while triggering a POST call from your client.
axios.post <-----> app.get
(There is no route for POST call which client is expecting)

res.redirect() does not end request and causes error: "Cannot set headers after they are sent to the client "

My route that handles get requests for the login page checks to see if the user is already logged in. If they are, redirect them to /userprofile, if not, render the login.ejs view.
From what I was reading, res.redirect() should end the http request, but in this example I've been getting some weird behavior. When the user is logged in, I get the error "Cannot set headers after they are sent to the client" multiple times. Here's the code:
app.get("/login", (req, res) => {
if (req.session.user) { res.redirect('/userprofile') };
res.render('login');
})
But I realized that if
I just include a return before res.redirect() or
negate the if statement and invert the order of the responses
the code works fine.
Could anyone explain why? Thanks
It is caused by you redirecting the user, to /userprofile before rendering login. A way you could avoid this would be to do the redirect frontend, in your fetch.
fetch('login', {
method: 'POST',
})
.then(() => {
window.location.href = '/userprofile'
})

How to post a url

I am trying to convert an image to a url and then post it to a database using axios.post like this:
this.setState({
file: URL.createObjectURL(event.target.files[0])
})
and then posting it like so:
axios
.post(`http://localhost:4000/items/${this.state.file}
my model is this:
let items = new schema ({
img: String
})
and my post controller:
router.post('/:urlImg', function (req, res) {
let b= new items ({
imageProof: req.params.urlImg
})
the error is basically POST 'url' 404 (Not Found):
xhr.js:184 POST http://localhost:4000/items/blob:http://localhost:3000/9045e921-4e7f-4541-8329-0b9cd65814c6 404 (Not Found)
however the thing to note is if I am using a simple url such as www.google.com, it works. however, I can't use https://
does anyone know how I can resolve this problem? Is there some other way to store and display an image?
You can simply url encode your image url as follow. When you just pass the url without encoding it first it forms a invalid url which contains https in the middle. So you have to encode it before passing
axios
.post(`http://localhost:4000/items/${encodeURIComponent(this.state.file)}
Or
Instead of sending it as a url parameter send it as a body parameter
axios.post('/user', {
urlImg: "http://your/image/url"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
For 2nd approach you might want to change the backend in order to extract the parameter from the request object.

How to add id and body to axios.PUT request?

I am using axios with REACT and wondering how I can use it to make a put request to update an object through the backend node/express API I have set up.
I need to be able to pass an id and a body and not sure of how to do so.
axios.put('/api/profile', id, body)
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err);
});
I do not think this will work as it takes the parameters of put(url, data, {headers})
The pattern for this is to making an axios request using the id of the entity/item that you want to update and return as shown:
axios.put(`/api/profile/${id}`, body); //using string interpolation
axios.put('/api/profile' + id, body); //using string concatenation
Then, on your express/node backend, you have a route that will match with this request's URI path and update that profile with the body. Not sure what you're using for your DB, but in pseudocode it would look like this:
/*
* 1. query profile Model for the specific profile
* 2. make sure to check if foundProfile is undefined or not.
* 3. update profile with body
* 4. Catch on errors
*/
router.put('/api/profile/:id', (req, res, next) => {
Profile.findbyId(req.params.id)
.then(foundProfile => foundProfile.update(req.body))
.catch(next);
})
As mentioned in a comment above, you could do this via the query string, but that would be odd/anti-pattern.

Nodejs ejs always asking for view when trying to redirect a url and receive its json data

I am trying to make a slack app and to complete Oauth2, I have to send the URI below and get a JSON response back in the body.
The problem is, every time I am trying to use the function request() in my app.get() function, ejs is always trying to go and get my views. Now I tried rendering my specific view for app.get() but then when I use request() again, ejs is again trying to get a view.
How can I redirect to another url from my app.get and receive the JSON. I can use req.redirect() but I don't know how to get the response back.
Please please help! Thanks
app.get('/', (req, res) =>{
var options = {
uri: 'https://slack.com/api/oauth.access code='+req.query.code+'&client_id='+client_id+'&client_secret='+client_secret,
method: 'GET'
}
request(options, (error, response, body) => {
var JSONresponse = JSON.parse(body)
if (!JSONresponse.ok){
console.log(JSONresponse)
res.send("Error encountered: \n"+JSON.stringify(JSONresponse)).status(200).end()
}else{
console.log(JSONresponse)
res.send("Success!")
}
})
})

Resources