How to write an Axios get request with a query? - javascript

I am using the MERN-Stack (React, NodeJS, React, Express, + MongoDB). I want to write a get-request with Axios to call up a route in the backend. But I only want to retrieve specific data from my database. For that I want to use a query.
My URL looks something like this:
'http://localhost:5000/users?name=john'
So I only get users whose name is John.
I wrote an axios-request, which looks like this:
axios
.get("http://localhost:5000/user/getown", { params: { username: this.state.username } })
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
I am not sure if I pass the query correctly.
In the backend I am using Express and Mongoose to get the date from my MongoDB. Therefore I am using this code:
router.route("/getown").get((req, res) => {
User.find({ username: req.query.username })
.then((user) => res.json(user))
.catch((error) => res.status(404).json("Error: " + error));
});
When I test the '/getown' route with Insomnia everything works correctly, so I think the mistake is in the frontend.

Related

How to read POST data in sveltekit

Hi I am beginner in sveltekit. I try to get post data in sveltekit here is my POST Request.
I am using axios to send post data.
const request = await axios
.post("/api/user", {
username,
email,
password,
repassword
})
.then((e) => {
console.log(e)
})
.catch((e) => {
console.error(e);
});
and this is my POST Endpoint:
// src/routes/user/+server.ts
export const POST = async({request}) => {
console.log(request)
return new Response(JSON.stringify({something: 1}))
}
this api working fine with GET methods.
Looks like the routes just don't match.
src/routes/user/+server.ts equates to just /user.

Cannot connect to Meaning Cloud API: key missing

I have tried connecting to the API but for some reason it says I am missing the key. I am including the key and when I log it in the console, I see the correct value. Even I test the value of the API key that is logged, in the Meaning Cloud test tool, and it works correctly. Since at the moment is only a test, I have added directly a URL of an article that I want to check with the API.
Test API: https://learn.meaningcloud.com/developer/sentiment-analysis/2.1/console
I am using axios but I also tried with node-fetch and got the same result.
Here is the full code of the project in Github:
https://github.com/schilate68/Natural_Language_Processing/blob/master/src/server/index.js
app.post('/test', function (req, res) {
console.log("In POST test API");
console.log(process.env.API_KEY);
axios
.post('https://api.meaningcloud.com/sentiment-2.1', {
key: process.env.API_KEY,
url: 'https://blog.logrocket.com/complete-guide-flutter-architecture/',
lang: "en"
})
.then(res => ({
status: res.status,
body: res.data
}))
.then(({ status, body }) => console.log(status, body))
.catch(error => {
console.error(error)
})
})

React Native how to send AsyncStorage data to MongoDB database?

I am not able to transfer user input which is stored in a AsyncStorage to my MongoDB database
I have a MongoDB database which I start from the terminal. The console output is the following so there should not be any problems:
Server started on PORT 5000
MongoDB Connected cluster0-shard-00-02.mhqqx.mongodb.net
After this I open my React Native app with expo go and go to my register screen where a new user profile should be created. I store every required user input (name, email, etc.) in a AsyncStorage in JSON format like this:
const nameString = JSON.stringify(name)
const emailString = JSON.stringify(email)
AsyncStorage.setItem('nameInput', nameString);
AsyncStorage.setItem('emailInput', emailString);
setName('');
setEmail('');
When I print the values of the AsyncStorages in the console, there is no error and the data is displayed correctly. So the user inputs are stored in the AsyncStorages.
But after this I try to transfer the AsyncStorage data to my MongoDB database by triggering the following function with a button onPress call:
const submitHandler = async (e) => {
if(password !==confirmpassword) {
setMessage('Passwords do not match')
} else {
setMessage(null)
try {
const config = {
headers: {
"Content-type": "application/json",
},
};
setLoading(true);
const { data } = await axios.post(
"/api/users",
{name, email, password},
config
);
setLoading(false);
} catch (error) {
setError(error.response.data.message);
}
}
console.log(email);
};
When I check the database, no new information is displayed in my database. The database is functional and the route which is defined should be correct. What could be the problem?
I am also able to create a new user from Postman like this:
I have tried to search some answers for this problem for a while now but without success. Help would be much appreciated!
You can do something like
await axios.post("/api/users",
{name, email, password},config)
.then(res=> console.log(res)
.catch(err => console.log("api error", err)
And see what you get in your corresponding terminal.
Note
Your API endpoint(api/users) is not valid. Add the same URL from Postman which you're using.

Axios response data is not saved with useState

While trying to fetch data from my express backend and MySQL database, with my react frontend using axios, it fails to set the fetched data using useState
my frontend function looks like this
const searchUser = () => {
Axios.post("http://localhost:3001/searchUser", {
username: username,
}).then((response) => {
if (response.data) {
setResult(response.data);
}
});
};
and my backend function looks like this
const searchUser = (req, res) => {
const keyword = req.body.username;
db.query(
"SELECT id,username FROM users WHERE username like ?",
"%" + keyword + "%",
(err, result) => {
if (err) {
res.json({ message: err });
console.log(err);
} else {
console.log(result);
res.json({ result });
}
}
);
};
I tried many methods while saving the data with the useState hook, I appreciate any help
While using Promises and then instead of async / await make sure to catch the errors if your fetch fails.
Unless you share with us the whole component that contains the searchUser function and how you defined the state i cannot pin point you on the error.
What i suggest you to do is adding a catch to your fetch by doing the following:
const searchUser = () => {
Axios.post("http://localhost:3001/searchUser", {
username: username,
}).then((response) => {
if (response.data) {
setResult(response.data);
}
}).catch((error) => {
console.error(error);
});
};
If any abnormalities has happened in your request the catch will tell you! Don't underestimate it's power.
Another path you can look into is console logging your output in front end searchUser function just before setting it in the state.
I did solve the problem, just by replacing res.json({ result }); to res.json(result); in the last line in my backend function

How to add conditional checks over ORM (sequelizejs) queries?

Suppose i have a table gameData {gameId, currentBoardLayout}, a get request like www.chess.com/asd123 is sent over to the server, where asd123 is my game id, I need to catch this id (asd123 which is my gameId) and check for it in my table (gameData) and implement the following logic :
srv.get('/:id', (req, res) => {
if ( gameData.findAll({where: {gameId: req.params.id} )
{ // Game room found
return currentBoardLayout
}
else
{ error : Invalid game id }
})
How can I achieve this?
Thanks
You can use Sequelize's findById method.
srv.get('/:id', (req, res) => {
gameData.findById(req.params.id)
.then(result => {
res.send(result)
})
.catch(() => {
res.send({
error: 'Could not find ID'
})
})
})
Here's what is happening:
Sequelize's findById method will return a promise. If it successful, you will get your item from the database back. If the item cannot be found, the catch method will fire.
res.send is Express' way of sending data back to the client.
It is worth checking out the Sequelize docs:
Using models
Querying

Categories

Resources