Cant get into GET request when sending data in the URL - javascript

Im testing my API with postman, when I try to send data in the URL Postman responds with 404 Not found. I guess Its the format but searching around I think its correct. Can anyone throw some light please?
But when I dont send any data in the URL it works just fine:
When I try to send data in the get request:
app.get("/mediciones/sigfox_libelium/:{device}", (req, res) => {
const { device } = req.params;
res.json("im in");
console.log("Im in");
console.log(device);
console.log(req.params.device);
When I send no data on the request works just fine(it crashes but its becouse its not finished yet):
app.get("/mediciones/sigfox_libelium", (req, res) => {
const { device} = req.params;
res.json("im in");
console.log("Im in");
console.log(device);
console.log(req.params.device);

My guess is you're using Express.js to build API right?
I think you use req.params in the wrong way.
If you want params name device
You have to use :device instead of :{device} in url path.
Like this
app.get("/mediciones/sigfox_libelium/:device", (req, res) => {
cosnt { device } = req.params // You can get device here
})

Related

Problem extracting data from NEDB database Node.JS

I have a NEDB Datastore called users which contains one line of information. I call a fetch request to retrieve the users from the server and I can tell that the request is being processed by debugging. However, the users.find() is not working and I have no idea why. When I tried the same code with an alternate datastore, it worked fine.
Here is my Javascript code:
//Client side JS
async function extractUsers() {
const userJ = await fetch('/getUser');
let user = await userJ.json();
header.innerHTML = "Welcome " + user + "!";
}
//Server Side JS
const users = new Datastore('users.db');
users.loadDatabase();
app.get('/getUser', (req, res) => {
users.find({}, (err, data) => {
res.json(data);
})
});
If you have any idea why this is happening or need more information, please let me know. Thanks!
I simply deleted the users.db file and restarted the server, manually re-entering the data and it seemed to work.

GET/POST methods on Express

I am configuring a server using express.
My question has nothing to do with the project itself because it is running great.
I just have a minor doubt about why I have to use GET when for me it makes more sense to use POST.
So, for short I am configuring an API key on the server side and fetching it on the client side so I can use it.
This is the snippet on the server side:
const apiKey = process.env.API_KEY;
console.log(`Your API key is ${apiKey}`);
const dataObject ={};
app.get('/api', (req,res) => {
res.send({key: apiKey})
})
app.get('/all', sendData = (req,res) => {
res.send(dataObject)
})
app.post('/addText', (req,res) => {
let newEntry = {
agreement = req.body.agreement,
subjectivity = req.body.subjectivity
}
dataObject = newEntry;
res.send(dataObject);
} )
And then on the client side I fetch on the '/api' path:
const getApiKey = async () => {
// Getting API key from server
const request = await fetch('/api');
try {
const data = await request.json();
console.log(data);
return data;
}catch(error) {
console.log('ERROR', error);
}
}
Ok, that's working and everything, but my question is:
On the first GET on the server side, I understand that I am sending the API key to the '/api' path so that I can retrieve this key with fetch on the client side. But if I am sending the api key to this path, why am I using GET and not POST?
Sorry if it seems a stupid question but I am having a hard time understanding the GET method.
Thanks!
You are not sending any API key to the server. The server is sending the API key to the client as a response. The client uses a GET request to get the API key from /api. The names of the methods (GET, POST, PUT, DELETE, ...) are from the perspective of the client.
"And then on the client side I fetch on the '/api' path:" No. First the client sends the request with
const request = await fetch('/api');
try {
const data = await request.json();
console.log(data);
return data;
}catch(error) {
console.log('ERROR', error);
}
This triggers the callback in
app.get('/api', (req,res) => {
res.send({key: apiKey})
})
and the server sends the response.
This code returns the API key from the server. It does not send it from the client to the server.
app.get('/api', (req,res) => {
res.send({key: apiKey})
}
The
res.send()
Function is constructing the response returned by the server to the client.
Usually, you use the GET method when the client has to read some data from the server, in this case, you want to read the API_KEY defined in the server. GET has no body, but every request may be parametric by passing parameters in the query string.
On the other hand, when you have to update or create an entity on the server, that's when POST (or PUT) enters into action. Here you pass your data in the body of the request.

Post-Redirect-Get in Express Node.js

I am trying to implement a Post-Redirect-Get design pattern into my code, which uses Express. What I have is:
var sessionVariable;
app.post('/user', function(req, res) {
sessionVariable = req.session;
// Sets a session variable to a token
sessionVariable.token = req.body.token;
// Redirect to /user
return res.redirect('/user')
});
app.get('/user', function(req, res) {
sessionVariable = req.session;
if(sessionVariable.token){
res.send('Logged in');
} else {
res.send('Not logged in');
}
});
What I expect to happen is when the user submits a POST request to /user, it will define sessionVarlable.token, then redirect to /user again where it checks if a token exists.
What ends up happening is I will submit the POST request, and through console loggging I can see that app.post fires, but it does not re-direct. Instead, it seems to get stuck on the page where the POST request was omitted.
What is the reason for this?
Edit: Any res will not fire under app.post, e.g. res.send('test') doesn't work.
I have posted this answer elsewhere: Understanding the "post/redirect/get" pattern
but here is the code that works for me:
app.post('/data', function(req, res) {
data = req.body;
res.redirect('/db.html');
});
Based on the info from the comments, you're making an AJAX request. Instead of making the client redirect from server-side, just do it client-side. Here's an example using Axios on the browser (you can do essentially the same thing with AJAX, just messier):
axios.post('/user', { token: 'tokenhere'}).then(function(response) {
// Status 200 means OK
if (response.status === 200) {
window.location.href = 'user'
}
})

Overcome login middleware in react

i am login from localhost use react to another localhost use express,
Hi Guys im using this code to post the login data via react:
handleSubmit(event) {
event.preventDefault();
var params = Object.entries(this.state).map(([key, val]) => `${key}=${val}`).join('&')
fetch("http://localhost:3006/login", {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'},
body: params
})
.then((response) => response.json())
.then((responseJson) => {
//this.props.history.push("/landing");
console.log("loggedin", responseJson);
})
}
and the other localhost the backend is :
router.post("/login", passport.authenticate("local",{successRedirect: "/landing",failureRedirect: "login"}) ,function(req, res){
console.log(req.body);
});
i need way to save my login data after i sent it so i can login to the page /landing.
normaly the code work when i remove the middleware.isLoggedIn from the landing page
router.get("/landing",middleware.isLoggedIn, function(req, res) {
so is there is any expert in react can help me to do it :)
One way to save user data (user session) is "WebTokens". Yow can use JsonWebToken to let the server recognize the user and know some data about him. This data is hashed and stored with the cookies in the browser. Any query from the browser (the client) to the server will be carrying this data and the server will read it and use any useful data.
For more info on how to use it with your express server take a deeper look at this example.

Why does the browser return unexpected end of input when I can get the API response from browser?

I have a very basic react front end and a very basic nodejs server.
I'm trying to validate the username and password on the server when the client clicks submit and then eventually redirect them to their dashboard.
Right now I am not able to go any further than sending the request for user data.
This is my very basic authentication function on the server, functions like authenticate and searchusers are not asynchronous.
// Authorization
app.get('/auth/:userId/:hash', function(req, res){
var id = req.params.userId.toString();
var hash = req.params.hash.toString();
var error = {
err: 'something went wrong!'
}
var user = dm.searchUser(id, users);
if (!user){
res.json(error);
}
var isAuthenticated = dm.authenticate(user, hash);
if (!isAuthenticated){
res.json(error);
}
if(isAuthenticated){
console.log('authed')
res.json(user);
}
});
and this is my client side react component method that handles the submit action of a form.
submit(e){
e.preventDefault();
const BASE_URL = "http://localhost:3001/auth/"
fetch(`${BASE_URL}${this.state.userId}/${this.state.password}`, {
method: 'GET',
mode: 'no-cors'
})
.then(response=>response.json())
.then(json=>{console.log(json)})
.catch((err)=>{
console.log(err)
})
}
From what I have tried, if I tried to send a request from my browser, the server does respond with my JSON data.
But when I try to do the same with my client, it gives back an error, can someone please help me out with what is going wrong?
[EDIT]
This is the error I get

Categories

Resources