Route handler in express is not invoking anything? - javascript

I have made a simple textbox which accepts
Youtube Video URL
which slices it's video ID and use fetch to send data to my express server. I am using Youtube Data API v3
//after clicking button sends data
//input fields are defined already.
const sendData = (event) => {
event.preventDefault();
const filterUrl = input2.value.indexOf('&') != -1 ? input2.value.slice(0, input2.value.indexOf('&')) : input2.value;
const url = new URL(filterUrl).searchParams.get("v");
fetch('/', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
urlname: url.toString()
})
})
.then(function(res) {
console.log(res)
})
.catch(function(error) {
console.log(error)
});
}
Here is my Express Handler :
//defined routes and PARAMETER variable is globally defined
app.route('/')
.get((req, res) => {
res.render('container/index', {
title: 'Hello User!',
content: 'Welcome to youtube Comment viewer'
});
})
.post((req, res) => {
console.log("hello")
PARAMETER = req.body.urlname;
console.log(PARAMETER);
res.redirect('/randomCommentView');
});
//get request
app.get('/randomCommentView', (req, res) => {
console.log("inside");
Comments(PARAMETER)
.then((data) => {
res.render('container/comment', {
Comment: 'fgfg'
})
}).catch(err => {
if (err) res.status(404).render('container/index', {
notFound: `Your request couldn't be completed ERR: ${err}`
})
})
console.log(req.body);
});
But when i submit my Youtube video url, The page stays on the same route.
Here's the image of my output:
So it seems like the routes are being called but the page URL is not changing in the web browser .Does anyone know the possible reason for this.
Thanks,
Regards.

Since you're using javascript to make your request, only the javascript will follow your redirection.
What you can do is instead of sending a redirection from the server, send a special code that will trigger a manual redirection (window.location.href = ...) in your client-side javascript code.

Related

POST method to express server returning 404 [duplicate]

This question already has an answer here:
Express routes parameters
(1 answer)
Closed last month.
I'm trying to send a POST to my server, in order to edit a user's details. I've made sure it's sending to the right URL, however get a 404 response. GET requests work fine, however my POST doesn't seem to get through for whatever reason. I've been searching for solutions for a while, with no luck hence posting here!
user.js (server side)
userRoutes.route('/user/update/:id').post(function (req, response) {
let db_connect = dbo.getDb("preview");
let myquery = { _id: ObjectId(req.params.id) };
let newValues = {
$set: {
name: req.body.name,
user_name: req.body.user_name
},
};
db_connect
.collection("users")
.updateOne(myquery, newValues, function (err, res) {
if (err) throw err;
console.log('user updated');
response.json(res);
})
});
middleware
export const updateUser = async (id, userDetails) => {
const endpoint = `${serverIp}/user/update/?id=${id}`;
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(userDetails)
})
const result = await response.json();
return result;
} catch (error) {
console.log(error)
}
}
and a simple function to handle submitting
function handleSave() {
const newUserDetails = {
name: accountHolder,
user_name: accountUsername
};
updateUser(userId, newUserDetails);
}
Under networking in dev tools I can see the URL is indeed correct, so I can't see why this isn't working
chrome dev tools
Any help would be greatly appreciate it!
I've tried sending a basic response (i.e. a string instead of object), changing the endpoint, and more all to no avail
It seems like you are passing the id as a query param and not as part of the path
const endpoint = `${serverIp}/user/update/?id=${id}`;
^
What I can see from first glance is that in server-side you are using request parameter for id, but in the client you're sending id as a request query

Problems with fetching react.js/node.js

I'm trying to pass some datas from frontend to backend.
Here the code lines....
FRONTEND
handleSubmit = (event) => {
alert('A form was submitted: ' + this.state);
fetch('http://localhost:5000/store-data', {
method: 'POST',
/*mode: 'cors',*/
headers: {
'Content-Type': 'application/json',
},
// We convert the React state to JSON and send it as the POST body
body: JSON.stringify(this.state)
}).then(function(response) {
console.log(response)
return response.json();
});
console.log("Sono entrato");
event.preventDefault();
}
BACKEND
app.post("/store-data", (req, res) => {
let data = { name: req.body.username };
console.log(data.name);
console.log(JSON.stringify(req.body));
res.json("Hello");
});
All the console.log works well.
But if I go on the "localhost:5000/store-data", I get this error:
"CANNOT GET /store-data/ PAGE NOT FOUND 404"
Thanks
I add tis code and now seems to work:
app.get("/store-data", (req, res) => {
let data = { name: req.body.username };
console.log(data.name);
console.log(JSON.stringify(req.body));
res.send("Hello");
});
But I have to keep both the app.get() and the app.post() to work.
I think that is not the correct way.
Thanks
I solve it. The problem was that i make a mistake with the fetch method and I get undefined in the return response.json.
Now in the post method res.send work.
It was an error on the Frontend code not in the Backend.
In my case I don't need anymore app.get(....), but only the app.post(.....).

Delete user endpoint using Fetch

I am building a user website, where the admin should be able to delete users.
My project is build using Azure SQL database.
I have in my controllers file, come up with an endpoint deleteUser
deleteUser
const deleteUser = (req, res) => {
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
const { id } = req.query
request.query(
`DELETE FROM users where User_ID = '${id}'`,
function (err, recordset) {
if (err) {
console.log(err);
} else if (!id) {
res.json("Please provide an ID")
} else {
res.json(`User with ID: ${id} has been deleted!`)
}
}
);
});
};
I am then trying to make a call to this endpoint using fetch and EJS.
My code in EJS script tag
<script>
document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {
e.preventDefault();
fetch('http://localhost:3000/deleteUser', {
method:'DELETE',
headers: {
"Content-Type": "application/json",
},
body: null
})
.then((response) => console.log(response))
.catch((e) => {
console.log(e)
})
})
</script>
I console log the response, so the route must be good, but it seems as it doesn't parse the ID into the fetch. What is the right way to approach this?
Thanks in advance!
Solution
I have come up with follow solution - which is not the best, but works.
document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {
e.preventDefault();
// delete user using fetch
const id = document.getElementById('userId').textContent
fetch(`http://localhost:3000/deleteUser?id=${id}`, {
method:'DELETE',
headers: {
"Content-Type": "application/json",
},
body: null
})
.then((response) => console.log(response))
.catch((e) => {
console.log(e)
})
})
Thanks for the contribution!
Should the id not be in the URL of the fetch request? You are asking for the id from the request params, so it should probably be appended to the path like
const id = wherever your id comes from;
fetch('http://localhost:3000/deleteUser?id=${id}...'
You'll need to get the user's id in your button method as well, but would need more of your code to see where that comes from.
Usually using an ID for deletion is best approach
fetch('http://localhost:3000/deleteUser/:id...'
However, you can pass id in anyway in body, params, query or even headers)

My sent data using axios is returned in config, not data

I am building my web app on NextJS NodeJS and Express, I am running two servers on localhost 3000 for next and 9000 for express.
I have a form with two input fields and I am sending the state with axios post to the url with data, on the server-side I am receiving that request and sending back the same received data as a response.
I get the response from server with data: success and my data in config.data
Why is my data in config data and how can I get it out from this JSON so I can pass it to a variable.
As for grabbing the data from the config.data, I have tried for loops but they either push 56 elements of 56 numbers to the empty array or don't do nothing.
Client side:
state = {
bank_name: '',
account_number: ''
}
...
onSubmit = (e) => {
e.preventDefault()
axios.post('http://localhost:9000/api/bank', {
bankName: this.state.bank_name,
accNumber: this.state.account_number
})
.then(res => {
console.log(res)
}).catch(err => console.log(err))
}
Server side:
router.post('/', (req, res) => {
const {reqData} = req;
res.send(reqData);
})
Console log from client side ( console.log(res) ):
{
config: {
url: "http://localhost:9000/api/bank",
method: "post",
data: '{"bankName":"some new bank","accNumber":"39276542934235"}'
},
data: "success",
headers: "...",
request: "...",
status: 200,
statusText: "OK",
__proto__: Object
}
...
When I target res.config.data.bankName I get undefined.
I believe this has to do with the server response being as it is, or not parsing the data server receives in the first place, or it is due to promises.
Any input would be helpful, thanks
That res.config.data is string so parse it first JSON.parse(res.config.data) and then access the bankName.
Also you must be using body-parser at the express end. And so post data resides in req.body you should send that back not the whole req IMO.
Express:
router.post('/', (req, res) => {
const reqData = req.body;
return res.send(reqData);
});
Axios: (returned data should be in res.data)
axios.post('http://localhost:9000/api/bank', {
bankName: this.state.bank_name,
accNumber: this.state.account_number
})
.then(res => {
console.log(res.data);
}).catch(err => console.log(err))
}

Redirecting to a node template

I'm pretty new to node and everything that happens around, but I'm trying to make a little admin panel. There will be a login page and after login if the user is an admin the page will redirect to dashboard.ejs.
I suppose I didn't do it the correct way because what I did don't work.
Let me show you what I did :
Let's start with my main routes for admin. So these can be accesses with /admin and /admin/dashboard. If I just go to /admin the page loads normally with the login forms.
router.get('/', (req, res) => {
res.render('../views/admin/admin.ejs')
})
router.get('/dashboard', admin_check, (req, res) => {
res.render('../views/admin/dashboard.ejs')
console.log('dashboard rendered...')
})
I have a simple login button that will do some checks in the database and finally run this to redirect to the dashboard :
fetch('/admin/dashboard', {
headers: {
auth_token: sessionStorage.getItem('token')
}
})
This will correctly trigger and let the console.log() run that comes from here :
router.get('/dashboard', admin_check, (req, res) => {
res.render('../views/admin/dashboard.ejs')
console.log('dashboard rendered...')
})
The thing is, the dashboard isn't loaded while the res.render() in fact executed.
There is an error in console though :
The resource from “http://localhost:8080/admin/scripts/admin-auth.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
I looked up a little bit what this was but I don't really understand anything about it.
Here is my full admin-auth.js file :
$('#login_form').submit(e => {
e.preventDefault()
fetch('/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
email: $('#login_email').val(),
password: $('#login_password').val()
})
})
.then(res => res.json())
.then(data => {
if (data.status === 200) {
sessionStorage.setItem('token', data.token)
sessionStorage.setItem('user', data.user)
fetch('/api/user', {
headers: {
auth_token: data.token
}
})
.then(res => res.json())
.then(data => {
if (data.user.admin) {
fetch('/admin/dashboard', {
headers: {
auth_token: sessionStorage.getItem('token')
}
})
}
})
} else {
console.log(data.error)
}
})
})
EDIT: So I used this instead :
res.sendFile(process.cwd() + '/src/views/admin/dashboard.ejs')
But the page still don't appear. Errors are gone and in the network management I get a 200 response but that's it

Categories