"message": "Unauthorized Access" is showing, get method is not working - javascript

when I post this method in my MongoDB database it's working properly, but when I wanted to get it it's showing {"message": "Unauthorized Access"} in my http://localhost:5000/my site. The thing which I wanted everything is ok. But get is not working
//server side code
app.post("/my", async (req, res) => {
const my = req.body;
const result = await myCollection.insertOne(my);
res.send(result);
});
app.get("/my", async (req, res) => {
const query = {};
const cursor = myCollection.find(query);
const services = await cursor.toArray();
res.send(services);
});
//client side code
const onSubmit = (data, event) => {
const url = `http://localhost:5000/service`;
fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((result) => {
setIsReload(!isReload);
if (result) {
alert("Add Successful");
}
});
const order = {
email: user.email,
name: event.target.name.value,
description: event.target.description.value,
price: event.target.price.value,
quantity: event.target.quantity.value,
};
axios.post(`http://localhost:5000/my`, order).then((res) => {
const { data } = res;
console.log(data);
if (data.insertedId) {
alert("Inserted");
}
event.target.reset();
console.log(res);
});
};

Related

why patch function not calling react native to node js

React Native
this my code. when i request for data push in database then react native App.js fetch function is not execute you can see my code and solve this bug...
this is my react native screen code where i function is not calling backend
App.js
const postdata = async () => {
const data = {cname, cphone, ccity, caddress, cemail, gender}
// 63064232cf92b07e37090e0a
const res = await fetch(`http://192.168.43.220:8000/Newcustomer/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
cname, cphone, ccity, caddress, cemail, gender
})
})
const data2 = await res.json();
console.log(data2);
if (!data2) {
window.alert('error in get data2');
}
else {
setdata(data2);
window.alert("Costomer Added")
navigation.navigate("Home")
}
}
Back End
Node js
this is my node js code. it code is properly working when i try to postman
app.js
app.patch('/Newcustomer/:id', async (req, res) => {
const _id = req.params.id;
getschema.findByIdAndUpdate(_id, {
$push: {
costomer:
{
cname: req.body.cname,
cphone: req.body.cphone,
ccity: req.body.ccity,
caddress: req.body.caddress,
cemail: req.body.cemail,
gender: req.body.gender
},
}
})
.then(data => {
res.status(201).json(data);
}).catch(err => {
console.log(err);
})
})

React Native - Variable does not update correctly when retrieving data from AsyncStorage

I'm trying to store and get data that I fetch from an API. The user is supposed to get a token on the login screen, and the token will be shown in an Alert dialog on home screen when the user press a button. But the token is not shown in the Alert dialog. the token is shown after I reload(not refresh the app. I used Live Server extension) the screen three times.
Login.js
const _userLogin = () => {
fetch(URLs._login, {
method: "POST",
headers, body,
})
}).then((response) => response.json())
.then((result) => {
if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
storeData(result.access_token, result.token_type);
navigation.navigate('HomeScreen');
} else {
Alert.alert("Error", result.message);
}
});
};
const storeData = async (accessToken, tokenType) => {
try {
await AsyncStorage.setItem('#access_token', accessToken);
await AsyncStorage.setItem('#token_type', tokenType);
await AsyncStorage.setItem('#user_auth', tokenType + " " + accessToken);
} catch (e) {
console.log(e);
}
}
Home.js [UPDATE]
const [inputs, setInputs] = React.useState({
userToken: '',
userPointsBalance: '',
expiringOn: '',
});
useEffect (() => {
_dashboard();
})
const getToken = async () => {
inputs.userToken = await AsyncStorage.getItem('#user_auth');
}
const _dashboard = () => {
getToken();
fetch(URLs._dashboard, {
method: "GET",
headers: {
'Authorization': inputs.userToken,
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then(async (result) => {
storeData(result.code, result.name, result.member_name, result.user_points_balance, result.expiring_on, result.status, result.token_id);
getData();
});
};
const storeData = async (code, name, memberName, userPointsBalance, expiringOn, status, tokenId) => {
try {
await AsyncStorage.setItem('#user_points_balance', userPointsBalance.toString());
await AsyncStorage.setItem('#expiring_on', expiringOn.toString());
} catch (e) {
console.log(e);
}
}
const getData = async () => {
const userPointsBalance = await AsyncStorage.getItem('#user_points_balance');
const expiringOn = await AsyncStorage.getItem('#expiring_on');
setInputs({userPointsBalance: userPointsBalance, expiringOn: expiringOn});
}
return (
<Text>{inputs.expiringOn}<Text>
)
i hope it works
.then(async(result) => {
if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
await storeData(result.access_token, result.token_type)
.then(res=>
navigation.navigate('HomeScreen')
)
} else {
Alert.alert("Error", result.message);
}
});

Body of fetch returning empty object in Next.js API endpoint call

I am having trouble with making an API call in Next.js that is deleting an item in a database. I am using the "body" field of the fetch to send a string to the API. The fetch call is being made in a Next.JS page and the API endpoint is in the API folder generated by Next.js. When I attempt the console.log the body from the request it is returning an empty object. Below will be the code for the page and then the code for the API endpoint. A screenshot of the console.log from the API endpoint will also be given.
Page
const handleRemoveItem = useCallback(async(event) => {
event.preventDefault()
var itemSKU = event.target.value;
const response = await fetch('/api/SB-RemoveProduct', {
method:'POST',
body: itemSKU
}).then((r) => {
return r
}).catch((err) => {
throw(err)
});
var deleteConfirm = await response.json();
console.log(deleteConfirm);
},[])
API endpoint
export default withSession(async (req, res) => {
var itemSKU = req.body
console.log("You are here 1");
console.log(itemSKU);
switch (req.method) {
case 'POST': {
var productRemoved = await removeProduct(itemSKU, req, res)
return productRemoved;
break
}
case 'GET': {
console.log('try writting a route')
break
}
case 'DELETE': {
console.log('try writting a route')
break
}
case 'UPDATE': {
console.log('try writting a route')
break
}
}
});
export const removeProduct = async (itemSKU, req, res) => {
var params = {
TableName: "products",
Key: itemSKU
}
console.log("You are here 2");
console.log(itemSKU); // this console.log and the one above both return {}
DB.delete(params, function(err, data) {
if (err) {
console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2));
res.status(200).send(data)
}
});
}
EDIT 1:
After receiving some feedback, I added headers with the 'Content-Type': 'text/plain', 'Accept': 'text/plain' and ended with the same result. I also verified that the variable that I am passing into the body is a string. Below will be page for the code updated.
const handleRemoveItem = useCallback(async(event) => {
event.preventDefault()
var itemSKU = event.target.value;
console.log(typeof(itemSKU));
const response = await fetch('/api/SB-RemoveProduct', {
method:'POST',
body: itemSKU,
mode: "cors",
headers: {
'Accept': 'text/plain',
'Content-Type': 'text/plain'
},
}).then((r) => {
return r
}).catch((err) => {
throw(err)
});
var deleteConfirm = await response.json();
console.log(deleteConfirm);
},[])
EDIT 2:
Following the suggestions from a solution below, I was able to return a different value for itemSKU than what I had before. This time, instead of the item being empty, it returned as undefined. The changes I made are below:
page:
const handleRemoveItem = useCallback(async(event) => {
event.preventDefault()
var itemSKU = event.target.value;
console.log(typeof(itemSKU));
const response = await fetch('/api/SB-RemoveProduct', {
method:'POST',
body: JSON.stringify({itemSKU}),
}).then((r) => {
return r
}).catch((err) => {
throw(err)
});
var deleteConfirm = await response.json();
console.log(deleteConfirm);
},[])
API Endpoint:
export default withSession(async (req, res) => {
var itemSKU = req.body.itemSKU //req.body.itemSKU is returning undefined.
console.log("You are here 1");
console.log(itemSKU);
switch (req.method) {
case 'POST': {
var productRemoved = await removeProduct(itemSKU, req, res)
return productRemoved;
break
}
case 'GET': {
console.log('try writting a route')
break
}
case 'DELETE': {
console.log('try writting a route')
break
}
case 'UPDATE': {
console.log('try writting a route')
break
}
}
});
export const removeProduct = async (itemSKU, req, res) => {
var params = {
TableName: "products",
Key: itemSKU
}
console.log("You are here 2");
console.log(itemSKU);
// DB.delete(params, function(err, data) {
// if (err) {
// console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
// } else {
// console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2));
// res.status(200).send(data)
// }
// });
}
remove the headers, including Content-type: plain/text, then...
In your request, change
body: itemSKU,
to
body: JSON.stringify({ itemSKU });
In your API, you can
console.log('req.body.itemSKU', req.body.itemSKU)
Eventually...
//client side
fetch('/api/...', { method: 'POST', body: JSON.stringify({...}))
.then(res => res.json())
.then(data => console.log('data', data));
//prints { value1: 'abc', value2: 'efg'}
Then on API side
export default async(req, res) => {
console.log('req.body.itemSKU', req.body.itemSKU);
res.json({ value1: 'abc', value2: 'efg'})
}

Send data to Express backend

I'm having trouble sending data to the Backend. I want to send data f1 to QueryBackend.js but when I try to console.log(req.body.f1) it's always undefined but in Services.js get the value.
Toolbar.js
handlePrintLetter = async(fieldName, fieldValue) => {
const { formId, selectedRows, displayData, onNotification } = this.props;
const idSelected = selectedRows.data.map(d => displayData[d.dataIndex].id);
const res = await getBookmarkDocument(idSelected); // Send Data to Backend
if (res.success) {
onNotification({ mode: 'success', text: 'success' });
} else {
onNotification({ mode: 'error', text: fieldName + ' ' + fieldValue });
}
}
Service.js
export const getBookmarkDocument = async (f1) => {
console.log(f1) // get value from Toolbar.js
const token = localStorage.getItem('token');
return axios.get(API + 'doc/show', { f1 },
{
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => response.data || [])
.catch((error) => {
ErrorAPI(error);
return [];
});
}
How to get data f1 in here?
QueryBackend.js
router.get('/show', async (req, res) => {
try {
console.log(req.body.f1) // undefined
const pool = await poolPromise;
const result = await pool.query('SELECT sid_ddocument_key FROM sid_ddocument WHERE sid_ddocument_key = $1', ['I WANNA PUT DATA 'f1' IN HERE']); // Put Data f1
res.status(200).json({
success: true,
data: result.rows
});
} catch (err) {
res.status(500).json({
success: false,
response: err.message
});
}
});
GET requests can't have bodies. Encode the data in the query string and read it with req.query
const f1 = 'example';
const API = 'http://example.com/';
const url = new URL(`${API}doc/show`);
url.searchParams.append("f1", f1);
console.log(url.toString());

OAuth2: how to get token?

I'm getting this error
RequestError: Error: Argument error, options.body
after sending a request. I saw this in the API:
grant_type = partner
partner_id = partner id
partner_secret = partner secret
This is the source code:
getToken() {
let data = {
grant_type: 'partner',
partner_id: config.id,
partner_secret: config.secret,
};
const url = config.url;
return this.postRequest(url, data)
.then((result) => {
console.log(result);
if (result) {
console.log(result);
return result;
}
})
.catch((err) => console.log(err));
}
postRequest(url, data) {
const options = {
uri: url,
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: data,
};
return request(options);
}
This code should return a token like this:
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer",
"expires_in":1119,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}
What's wrong with the code?
Data should be an query string!
getToken() {
let data = {
grant_type: 'partner',
partner_id: 'config.id',
partner_secret: 'config.secret',
};
data = querystring.stringify(data);
const url = config.url;
return this.postRequest(url, data)
.then((result) => {
if (result) {
console.log(result);
return result;
}
})
.catch((err) => console.log(err));
}

Categories