Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'validateStatus' in - mongodb

I am getting ** Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'validateStatus' in 5f8425a33a14f026f80133ed** where 5f8425a33a14f026f80133ed is the id passed to the axios url
I want to display the services based on the user id. My url works perfectly in postman but when i access it from the veux store it gives an error.
services.js (store)
import axios from 'axios';
const state = {
services : {},
status: '',
error: null
};
const getters = {
services : state => { return state.services }
};
const actions = {
async fetchServices({commit}, userId) {
let res = await axios.get('http://localhost:5000/api/services/displayUser' , userId)
commit('setProducts', res.data)
return res;
}
};
const mutations = {
setProducts (state, items) {
state.services= items
},
};
export default {
state,
actions,
mutations,
getters
};
This is how I am calling the action :
computed: {
...mapGetters(["services"]),
},
methods: {
...mapActions(["fetchServices"]),
getData(){
this.fetchServices(this.user._id)
},
},
async created() {
await this.getProfile();
await this.getData();
}
The axios route is defined as
router.get('/displayUser', (req,res) => {
const query = user = req.body ;
Services.find(query)
.exec((err, services) => res.json(services))
})
the error screenshot :
Error screenshot

GET request should not have a body. Either use query params, indicate an id in a path, or use POST request.
In case of query params this may look like this:
let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { userId })
router.get('/displayUser', (req,res) => {
const query = user = req.query;
Services.find(query)
.exec((err, services) => res.json(services))
})

This worked for me too:
In front end: Vue Js
let res = axios.get("http://localhost:3000/api/v1/role/getRoleByName",
{ params: { roleName: "name of role you want to send as params" },
});
In back end: Node Js
router.get('/getRoleByName', (req,res)=>{
let roleName = req.query.roleName;
roleModule.getRoleByName(roleName).then(data =>{
response.json(res,data)
}
).catch(err=> {
response.badRequest(res, err);
})
});

it's a silly mistake axios.post req.
async addTodo({ commit }, title) {
try {
const res = await axios.post(BASE_URL, { title, complete: false });
commit("newTodo", res.data);
} catch (err) {
console.log(err.message);
}
},

Related

Mongoose Error stating that it cannot populate a path because its not in my schema - but im not populating anything?

I have two routes in my server. Both routes are identical minus one using $push and one using $pull. The $pull route works as it should but always responds with an error of
"MongooseError: Cannot populate path scenes because it is not in
your schema. Set the strictPopulate option to false to override."
while the $push route works perfect and responds accordingly. I am very confused as to why I am getting a populate error considering I am not populating? I do have a 'scenes' property but not in either Model being used in these routes.
router.put('/scene/:sceneId/addactor/:actorId', async (req, res) => {
const actorId = req.params.actorId;
const sceneId = req.params.sceneId;
try {
const actor = await Actor.findById(actorId);
await Scene.findByIdAndUpdate(sceneId, { $push: { actors: actor } }, { new: true }).then(dbSceneData => {
res.status(200).send(dbSceneData);
})
} catch (error) {
res.status(400).send(`An Error Ocurred: ${error}`);
}
});
router.put('/scene/:sceneId/removeactor/:actorId', async (req, res) => {
const actorId = req.params.actorId;
const sceneId = req.params.sceneId;
try {
const actor = await Actor.findById(actorId);
await Scene.findByIdAndUpdate(sceneId, { $pull: { actors: actor } }, { new: true }).then(dbSceneData => {
res.status(200).send(dbSceneData);
})
} catch (error) {
res.status(400).send(`An Error Ocurred: ${error}`);
}
});

How can i make the interceptor run a function on error exept for one specific request?

this is my interceptor:
axios.interceptors.response.use(
(response) => {
if (error.response?.status === 403) {
unstable_batchedUpdates(() => {
// to force react state changes outside of React components
useSnackBarStore.getState().show({
message: `${i18n.t('forbidden')}: ${error.toJSON().config.url}`,
severity: 'error',
})
})
}
return Promise.reject(error)
}
)
I want this behavior all the time except when I make this specific call or at least except every head call
export const companiesQueries = {
headCompany: {
name: 'headCompany',
fn: async (companyId) => {
return await axios.head(`/companies/${companyId}`)
},
},
fixed by applying these changes to the api call:
const uninterceptedAxiosInstance = axios.create()
headCompany: {
name: 'headCompany',
fn: async (companyId) => {
return await
uninterceptedAxiosInstance.head(`/companies/${companyId}`)
},
}

Copy nested objects from Axios response to my React-native hook?

Im simply trying to copy the Nested objects i get back from the axios GET request to my react-native hook. Not straightforward it seems. Data would look something like this for example:
[
{
_id: 61242b08013a5f26bd1b2d47,
user: '6110675d65e1528d03a8bce6',
totalCalories: 7,
totalProtein: 7,
createdAt: 2021-08-23T23:11:04.076Z,
updatedAt: 2021-08-24T00:53:38.621Z,
__v: 0
},
{
_id: 6125990e9669cc6b466c37b5,
user: '6110675d65e1528d03a8bce6',
__v: 0,
createdAt: 2021-08-25T01:12:44.343Z,
totalCalories: 2,
totalProtein: 2,
updatedAt: 2021-08-25T01:14:01.439Z
}
]
However, i get a component exception: undefined is not an object error, as well as a 404 error when trying to access it via historyData in my frontend. Here is my component which renders the history screen in my iOS app:
Frontend:
const History = () => {
const [currentUsersID, setCurrentUsersID] = React.useState("");
const [historyData, setHistoryData] = React.useState();
// Gets the current user's ID from local storage
const getData = async () => {
try {
const value = await AsyncStorage.getItem("#storage_Key");
if (value !== null) {
setCurrentUsersID(value);
}
} catch (error) {
console.log("Error reading AsyncStorage value -> " + error);
}
};
getData();
async function getHistory() {
try {
const response = await axios.get("http://localhost:5000/daysLog/getLog/" + currentUsersID);
setHistoryData(() => {
return response.data;
});
} catch (error) {
console.log("ERROR (getHistory) -> " + error);
}
}
useFocusEffect(
React.useCallback(() => {
getHistory();
})
);
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" />
<Text style={{ color: "white" }}>
History: {historyData[0].totalCalories} // ERROR HERE
</Text>
</SafeAreaView>
);
};
Backend:
const router = require("express").Router();
let daysLog = require("../models/daysLog.model");
// getting the user's existing daysLogs
router.route("/getLog/:userID").get((req, res) => {
daysLog
.find({
user: req.params.userID,
})
.then((logs) => res.json(logs))
.catch((error) =>
res.status(400).json("Error (dayLog/GET) -> " + error)
);
});
historyData[0].totalCalories is throwing that because it will take time for it to get fetched while you're waiting for a response. You should have a block to test if historyData is not nul before you render the result.
Also get history focus effect relies on currentUser being valid but there's no expression that ensures it the way you wrote it. At best it's a race condition. Consider changing your focus effect to be a regulaf effect and make the currentUserId it's dependency.
Then inside of it to you can check if currentUserId is not null and start fetching get history accordingly.

How to convert from get.JSON to fetch

I have this working fine with get.JSON but when I try and use the fetch API instead, it gives me the error "Required parameter: part".
export const fetchYoutube = () => {
return dispatch => {
fetchAsync()
.then(data => console.log(data))
.catch(reason => console.log(reason.message))
dispatch({
type: INCREMENT
})
}
}
async function fetchAsync () {
var query = {
part: 'snippet',
key: 'AIzaSyA3IHL73MF00WFjgxdwzg57nI1CwW4dybQ',
maxResults: 6,
type: 'video',
q: 'music'
}
let response = await fetch('https://www.googleapis.com/youtube/v3/search', {
data : query,
method: 'GET'
});
let data = await response.json();
return data;
}
How do I pass the query object using the fetch API?
Try attaching the query as params:
replace:
let response = await fetch('https://www.googleapis.com/youtube/v3/search', {
data : query,
method: 'GET'
});
with:
var url = new URL("https://www.googleapis.com/youtube/v3/search"),
query = {
part: 'snippet',
key: '#####################################',
maxResults: 6,
type: 'video',
q: 'music'
}
Object.keys(query).forEach(key => url.searchParams.append(key, query[key]))
let response = await fetch(url)
Setting query string using Fetch GET request

How to invoke openwhisk action within openwhisk platform on bluemix?

I have created two actions on OpenWhisk on Bluemix. Both independently work fine when I can call them from outside the OpenWhisk platform. But I want to call action1 from within action2, and am using the following syntax:
var openwhisk = require('openwhisk');
function main(args){
const name = 'action2';
const blocking = true;
const params = { param1: 'sthing'};
var ow = openwhisk();
ow.actions.invoke({name, blocking, params})
.then(result => {
console.log('result: ', result);
return result; // ?
}).catch(err => {
console.error('failed to invoke actions', err);
});
}
But I get an empty result and no console messages. Some help would be great.
Update1:
When adding as suggested the return option, to return the Promise of OpenWhisk, as follows:
return ow.actions.invoke({name, blocking, params})
.then(result => {
console.log('result: ', result);
return result;
}).catch(err => {
console.error('failed to invoke actions', err);
throw err;
});
the response value of action2 is not as expected but contains:
{ "isFulfilled": false, "isRejected": false }
where I expect the return message of action2 (which reads a Google Sheets API) and parses the result:
{
"duration": 139,
"name": "getEventCfps",
"subject": "me#email.com",
...
"response": {
"result": {
"message": [
{
"location": "Atlanta, GA",
"url": "https://werise.tech/",
"event": "We RISE Women in Tech Conference",
"cfp-deadline": "3/31/2017",
...
}
]
},
"success": true,
"status": "success"
},
...
}
So I am expecting I am not parsing the '.then(result' variable in action1 correctly? cause when I test action2 separately, from outside OpenWhisk via Postman or API Connect, or directly by 'Run this action' in OpenWhisk/Bluemix it returns the correct values.
Update2:
Alright solved. I was calling the ow.actions.invoke to action2 in a function that was called within the action1, this nesting of returns, caused the issue. When I moved the invoke code directly in the main function, all resolved as expected. Double trouble when nesting promises and returns. Mea culpa. Thanks everyone
You need to return a Promise in your function try this
var openwhisk = require('openwhisk');
function main(args){
const name = '/whisk.system/utils/echo';
const blocking = true;
const params = { param1: 'sthing'};
var ow = openwhisk();
return ow.actions.invoke({name, blocking, params})
.then(result => {
console.log('result: ', result);
return result;
}).catch(err => {
console.error('failed to invoke actions', err);
throw err;
});
}
If you just want to invoke the action:
var openwhisk = require('openwhisk');
function main(args) {
var ow = openwhisk();
const name = args.action;
const blocking = false
const result = false
const params = args;
ow.actions.invoke({
name,
blocking,
result,
params
});
return {
statusCode: 200,
body: 'Action ' + name + ' invoked successfully'
};
}
If you want to wait for the result of the invoked action:
var openwhisk = require('openwhisk');
function main(args) {
var ow = openwhisk();
const name = args.action;
const blocking = false
const result = false
const params = args;
return ow.actions.invoke({
name,
blocking,
result,
params
}).then(function (res) {
return {
statusCode: 200,
body: res
};
});
}