How to pass information from Node to React - javascript

I have an object i need to parse to React.
I'm trying to get the "rows" object (in the node function) over to a React State.
The 2 piece of code below are on different pages!
The other issue is
GET http://localhost:3000/new net::ERR_CONNECTION_REFUSED
I am currently running these both locally
React http://localhost:3001/
Node - http://localhost:3000/
There have been SIMILAR questions to this but I can't find an answer with both issues!
Thanks
router.get("/new", (req, res) => {
let parentList = sql.fetchAllParents(function(err, rows) {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3001");
if (err) throw err;
res.render('new', {parents: rows});
});
});
componentDidMount() {
fetch(`http://localhost:3000/new`).then(response => {
console.log(response)
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data,'data');
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
}

Send response from node "new" api. Like this:
router.get("/new", (req, res) => {
......
......
res.send({status:200,parents:data})
});

Related

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 sort NeDB database in get response? (Javascript callback/arrow function syntax confusion)

I have an express server and a simple NeDB database. I can successfully get the whole database like so:
app.get('/api', (request, response) => {
//queuery the database for everything
db
.find({}, (error, data) => {
if (error) {
response.end();
console.log(error)
return;
}
console.log(data)
response.json(data)
})
But I noticed the results are, for some reason, not the same order as the database file. I want to sort by one of the timestamps. The database looks like:
...
{"lat":1,"lon":7,"timestamp":1585781054239,"_id":"3cZvJfQyLEXK0SZo","createdAt":{"$$date":1585781054240},"updatedAt":{"$$date":1585781054240}}
{"lat":1,"lon":2,"timestamp":1585781047536,"_id":"DN9bpd1FygEowgtc","createdAt":{"$$date":1585781047538},"updatedAt":{"$$date":1585781047538}}
{"lat":1,"lon":6,"timestamp":1585781052398,"_id":"Dzp6x0xo3QM960Rm","createdAt":{"$$date":1585781052400},"updatedAt":{"$$date":1585781052400}}
{"lat":1,"lon":5,"timestamp":1585781051174,"_id":"KswtMYzV2QBE3xkb","createdAt":{"$$date":1585781051176},"updatedAt":{"$$date":1585781051176}}
...
I admittedly haven't quite wrapped my head around how the callbacks work in this code. I have tried something like the following but it returns a 500 GET error to the client and returns "TypeError: Cannot read property 'sort' of undefined" to the server:
app.get('/api', (request, response) => {
//queuery the database for everything
db
.find({}, (error, data) => {
if (error) {
response.end();
console.log(error)
return;
}
// console.log(data)
// response.json(data)
})
.sort({ createdAt: -1 }, (data) => {
console.log(data)
response.json(data)
});
});
I wonder if it should be nested in the .find() function but at this point I'm quite in over my head and I believe I'm just not understanding the syntax. I have found examples of sorting but not in this context.
You can write something like this to sort it via timestamp:
database.find({}).sort({"timestamp":-1}).exec(function(err, data) {
if (err) {
response.end();
return;
}
console.log(data);
});

Can not do get request method because data says [object object]

I'm trying to do a get request method in Vue and Express to get data based on my v-model.
Below is my code that tries to send data to express.
getResult() {
axios
.get(
`${process.env.VUE_APP_API}/hospita/result/` +
{
hosp_name: "SAMPLE"
}
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
and here is my get request method that receives the data coming from vuejs
router.get('/result/', (req, res) => {
const sql = "SELECT * FROM \
ND_HOSP WHERE hosp_ptype = 'h' AND hosp_name LIKE ?";
console.log(req.body)
myDB.query(sql, ['%' + req.body.hosp_name + '%'], (err, result) => {
if (err) {
console.log(err)
} else {
try {
res.send(result);
/* console.log(result) */
} catch (err) {
res.send(err)
}
}
})
})
but it gives me error and says
http://localhost:9002/hospita/result/[object%20Object]
In your getResult() let's to change method to post and + to , for passing your data in body. You can look at this code below:
getResult() {
axios
.post( // <= change method to post
`${process.env.VUE_APP_API}/hospita/result/`, // change `+` with `,`
{
hosp_name: "SAMPLE"
}
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
After that, don't forget to change your router method from get to post. You can look at this code below:
// change method `get` to `post`
router.post('/result/', (req, res) => {
const sql = "SELECT * FROM \
ND_HOSP WHERE hosp_ptype = 'h' AND hosp_name LIKE ?";
console.log(req.body)
myDB.query(sql, ['%' + req.body.hosp_name + '%'], (err, result) => {
if (err) {
res.send(err)
} else {
res.send(result);
}
})
})
Make sure, because we're use the req.body, so, don't forget to add body parser in your server.js or app.js. It's will looks like this code below:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
I hope it can help you.
problem is here: res.send(result);
result is not containing json data, it is containing any other object or blank object like {}.
so first of all try to see what is inside the result using console.log().
most of the time for the such cases two functions are very useful.
JSON.stringify(object);
JSON.parse(strobj);

I can`t delete anything from my MongoDB [duplicate]

I'm currently working on my first node.js rest api with express, mongodb (atlas cloud) and mongoose, when i try to make a .remove request i get this error:
{
"error": {
"name": "MongoError",
"message": "Cannot use (or request) retryable writes with limit=0",
"driver": true,
"index": 0,
"code": 72,
"errmsg": "Cannot use (or request) retryable writes with limit=0"
}
This is my request:
router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
}); ;
});
The findOneAndRemove() function would work more accordingly since its specific to the filtering method passed in the function .findOneAndRemove(filter, options) to remove the filtered object. Still, if the remove process is interrupted by the connection the retryRewrites=true will attempt the execution of the function when connected.
More information here
When using retryRewrites set to true tells the MongoDB to retry the same process again which in fact can help prevent failed connections to the database and operate correctly, so having it turn on is recommended.
More info here
If you are using Mongoose 5^ and MongoDB 3.6 your code is better written like:
mongoose.connect('mongodb.....mongodb.net/test?retryWrites=true', (err) => {
if(err){
console.log("Could not connect to MongoDB (DATA CENTER) ");
}else{
console.log("DATA CENTER - Connected")
}
});// CONNECTING TO MONGODB v. 3.6
router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.findOneAndRemove({ _id: id })//updated function from .remove()
.exec()
.then(result => {
res.status(200).json({
message: "Product Removed Successfuly"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
}); ;
});
I just changed the true to false in retryWrites=true and it worked. Is that a good approach? Or there is a better way to solve this problem?
retryWrites=true is a good thing, a workaround for this incompatibility is to use findOneAndRemove instead of remove (looks like you're using mongoose)

error: syntax error at or near "$"

I am currently checking out Vue and am doing a little refactor on a personal project.
I am running into some problems with my API.
The two technologies involved are axios which I am using to send requests to my API, which talks to a postgres database using pg-promise.
The api call...
function add (entry, cb) {
const length = entry.content.length
entry.title = `${entry.content.substring(0, 32)}`
axios.post('/api/notes', entry).then(cb)
}
here, entry is and object { title, content, prio, status, context }
the pg-promise endpoint
export const createNote = (req, res, next) => {
db.none('insert into entries(title, content, prio, status, context)' +
'values( ${title}, ${content}, ${prio}, ${status}, ${context})',
req.body)
.then(() => {
res.status(200)
.json({
status: 'success',
message: 'Inserted one entry'
})
}).catch(err => next(err))
}
here, req.body is undefined
I don't know why I am getting undefined.
Does this error log help?
I was reading through the documentation at axios and could not seem to find anything wrong with my api call, figured I would post something here.
Thanks!
req.body It has the following structure [{.....}]
for pg-promise need {....}
Solution to the problem req.body[0]
export const createNote = (req, res, next) => {
db.none('insert into entries(title, content, prio, status, context)' +
'values( ${title}, ${content}, ${prio}, ${status}, ${context})',
req.body[0])
.then(() => {
res.status(200)
.json({
status: 'success',
message: 'Inserted one entry'
})
}).catch(err => next(err))
}

Categories

Resources