How to send react native text field value as JSON.stringify - node.js

I have code like this:-
export default class TextField extends Component {
constructor(props) {
super(props);
this.state = {
userID: '',
userName: '',
userGmail: '',
userTNumber: '',
};
}
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
} <TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={userID => this.setState({userID})}
value={this.state.userID}
autoCapitalize="none"
/>
</View>
}
I Need To Send My Text Input To My Node BackEnd...
I Don't Know How To Send My Data Using This Fetch Function
**
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
};
**
I Don't Know How To Put My Text Input Into,
body: JSON.stringify({}),
This Is My BackEnd To Post My Data:-
app.post('/send-data', (req, res) => {
const customer = new Customer({
userID: req.body.userID,
userName: req.body.userName,
userGmail: req.body.userGmail,
userTNumber: req.body.userTNumber,
});
customer
.save()
.then(result => {
console.log(result);
res.send(result);
})
.catch(err => {
console.log(err);
});
});
Can You Help Me ..?
ThankYou..!

If I understood correctly, you want to pass your data in the following format:
{
"userID": 1,
"userName": "John Doe",
"userGmail": "john.doe#example.com",
"userTNumber": "1234"
}
You want to use the data from your state and pass it to the fetch function, like so:
export default class TextField extends Component {
constructor(props) {
super(props)
this.state = {
userID: "",
userName: "",
userGmail: "",
userTNumber: "",
}
}
addCustomer = () => {
const { userID, userName, userGmail, userTNumber } = this.state
fetch("http://localhost:3000/send-data", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userID, userName, userGmail, userTNumber }),
})
}
render() {
return (
<TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={(userID) => this.setState({ userID })}
value={this.state.userID}
autoCapitalize="none"
/>
)
}
}

Related

Store Json object in mongoDb with fetch request

I have a User model and trying to add education field to mongoDB as json object as follows,
User model
education: {
"school": String,
"years":Number
},
Client
//add Education section
const updateEducation = async (e) => {
e.preventDefault();
await fetch(`http://localhost:5000/api/user/updateEducation`, {
method: "PUT",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid, educationSchool: educationSchool,
educationYearText: EducationYear}),
})
.then((res) => res.json())
.then((data) => {
console.log("User education is:", data.education +""+data.educationYear);
});
};
Server
const updateEducation = async (req, res) => {
try {
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$set: {
'education.school': req.body.educationSchool,
'education.years': req.body.educationYearText,
},
}
);
if (!user) {
res.status(404).json("user not exist");
}
res
.status(200)
.json({
education: user.education.School,
educationYear: user.education.years,
});
} catch (error) {
res.status(500).send({ error: error.message });
}
};
When im hitting this endpoint in postman http://localhost:5000/api/user/updateEducation
{
"userid":"63bbe4df75dca5aac7576e47",
"educationSchool":"Test college",
"educationYearText":"2018"
}
Im getting {
"error": "Plan executor error during findAndModify :: caused by :: Cannot create field 'school' in element {education: []}"
}
Whats wrong?
You should $push into an array:
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$push: {
education: {
school: req.body.educationSchool,
years: req.body.educationYearText,
}
},
},
{ new: true }
);

Finding items with attribute value match excluding another value in Sequelize

I have this code :
module.exports.MyFunction= async (req, res) => {
let token = req.body.token;
let decoded = jwt_decode(token);
let email = decoded.email;
let data = req.body;
let searchUser = data.user;
try {
let user = await User.findAll({
where: {
[Op.or]: [
{ firstName: searchUser },
{ lastName: searchUser },
{ email: searchUser },
{ publicKey: searchUser },
],
},
attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
}).then((response) => {
return response;
});
res.json({ user });
} catch (err) {
res.json({ err });
}
};
If I run that code, I get all the users that match with the value passed in searchUser.
What I want to do is to exclude the user object that have a specific email.
For instance, if have multiple users named Michel, I want to get all the users with an email address different of the email variable declared at the top of the function, even if their fisrtName matches.
Problem solved by doing this :
module.exports.MyFunction = async (req, res) => {
let token = req.body.token;
let decoded = jwt_decode(token);
let loggedUserEmail = decoded.email;
let data = req.body;
let searchUser = data.user;
console.log(searchUser);
try {
let user = await User.findAll({
where: {
[Op.or]: [
{
firstName: {
[Op.startsWith]: searchUser,
},
},
{
lastName: {
[Op.startsWith]: searchUser,
},
},
{
email: {
[Op.startsWith]: searchUser,
},
},
{
publicKey: {
[Op.startsWith]: searchUser,
},
},
],
email: {
[Op.ne]: loggedUserEmail,
},
},
attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
}).then((response) => {
return response;
});
res.json({ user });
} catch (err) {
res.json({ err });
}
};

How to terminate My function, it is working but never ending

I use the api mangopay for my app. The function to transfered worked but it never end until I refresh my page. I have no error code, the function still working but we can't get the message: 'the money is transfered'
Maybe I forgot something on my function ?
transfertMangoReferent: (req, res) => {
Serveur.findOne(
{ email: req.body.email },
"mangoWallet abonne",
(err, user) => {
if (user.abonne === true) {
api.Transfers.create(
{
AuthorId: req.user.mangoID,
DebitedFunds: {
Currency: "EUR",
Amount: req.body.amount * 100,
},
Fees: {
Currency: "EUR",
Amount: req.body.amount * 100 * 0.15,
},
DebitedWalletId: req.user.mangoWalletReferent,
CreditedWalletId: user.mangoWallet,
Tag: "Versement du pot Commun",
},
(model) => {
(error) => {
if (error) {
res.status(500).json({
message: "An error has occured with MANGO users",
});
}else{
res.json(model)
}
};
}
);
} else {
api.Transfers.create(
{
AuthorId: req.user.mangoID,
DebitedFunds: {
Currency: "EUR",
Amount: req.body.amount * 100,
},
Fees: {
Currency: "EUR",
Amount: req.body.amount * 100 * 0.25,
},
DebitedWalletId: req.user.mangoWalletReferent,
CreditedWalletId: user.mangoWallet,
Tag: "Versement du pot Commun",
},
(model) => {
(error) => {
if (error) {
res.status(500).json({
message: "An error has occured with MANGO users",
});
} else {
res.json(model)
}
};
}
);
}
}
);
},
On my network when i click to my button validate i have just the code 200
I can give you also my fetch in a react js
<Button
className="CollectButton"
type="submit"
onClick={() => {
const headers = new Headers({
"Content-Type": "application/json",
Authorization: "bearer " + localStorage.getItem("token"),
});
const data = {
email: element.serveurMail,
amount: this.state.referent.amount,
};
const options = {
method: "POST",
headers: headers,
body: JSON.stringify(data),
};
fetch("https://back-end.osc-fr1.scalingo.io/serveur/referentTransfert", options)
.then((response) => {
return response;
})
.then(
(data) => {
console.log(data);
},
(error) => {
console.log(error);
}
);
}}
>
Envoyez
</Button>

Node update not working, format is wrong while send to api

I try to update my data from Angular to Node.js
component.ts
updatefunction(id,data){
console.log("component",data);
//component {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
this.uAdminService
.updateUser(id,data).subscribe(
result => {
//console.log(result.json());
},
error => {
console.log(error.json());
}
);
}
in myservice.ts
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
my nodejs controller
router.put('/:id', VerifyToken, function (req, res) {
console.log(req.body);
//{'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'}
User.findByIdAndUpdate({_id:req.params.id}, req.body, {new: true}).select("-password")
.then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving Report."
});
});
});
my req.body console like this {'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'} but i pass from angularjs in this format {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
I don't know why it's converting so that it's not update to db
if i console from api it will like this { name: "Test",email: "test123#gmail.com"}
Update myservice.ts like below:
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
Changed the Content-Type to application/json as you are sending a json formatted data and not form data.

Provisional headers are shown

I am using Extjs in web and node.js in the api side. I called the api defined, from the web. I passed params and required data as request, but its showing the below error and request is unsuccessful.
Here is the api call code:
Ext.Ajax.request({
url: "http://localhost:3000/update-fund",
method: "POST",
dataType: 'json',
params: {
userId: userDocGlobal.id
},
headers: {
'Content-Type': 'application/json'
},
jsonData: {
fundId: PECalculator.selectedFund,
fundDate: getAiqDateFromPicker(Ext.getCmp("currentCalculationDateFundLevel")),
fundData: fund,
ownerId: userDocGlobal.companyid,
lpId: userDocGlobal.companyid,
role: userDocGlobal.role,
userId: userDocGlobal.id,
companyid: userDocGlobal.companyid
},
success: function (response) {
if (callback) {
callback(response);
}
if(userRole === "FREE"){
moduleObj.setFundNameAndCalcDateForFreeUser();
}
},
error: function () {
if (errorCallback) {
errorCallback();
}
}
})

Resources