getting Request failed with status code 404 with axios PUT - axios

I am currently developing a small exchange rate app with Vue 3 and facing a small issue with axios.
The GET request to the endpoint works like a charm, however the PUT doesn't.
This is my axios definition of the endpoint, which I simulate it with json-server.
axios.defaults.baseURL = "http://localhost:3000";
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.put["Content-Type"] = "application/json";
The JSON response looks like this:
{
"conversion": [
{
"base": "USD",
"rates": {
"EUR": 0.948434,
"GBP": 0.795324,
"USD": 1,
"CNY": 6.6085
}
},
{
"base": "EUR",
"rates": {
"USD": 1.0543696,
"GBP": 0.838565,
"EUR": 1,
"CNY": 6.967802
}
}
]
}
The GET request to the endpoint looks like this:
async getRates() {
await this.axios.get("/conversion/").then((result) => {
this.conversion = result.data;
this.conversionLoaded = true;
this.getRatesForBase(this.selected);
});
},
However, the PUTrequest throws an 404 error.
editValues() {
this.keys.forEach((key, index) => {
this.editRates(key, this.values[index]);
});
},
async editRates(key, value) {
await this.axios
.put("/conversion", {
base: this.selected,
rates: { [JSON.stringify(key)]: value },
})
.then((resp) => {
console.log(resp.data);
})
.catch((error) => {
console.log(error);
});
},
This is how the payloads looks like, driven from the loop:
{
"base": "EUR",
"rates": {
"GBP": 0.838565
}
}
{
"base": "EUR",
"rates": {
"CNY": 6.967802
}
}
I understand the meaning of the 404 error. Everything looks good to me, but I can't make it work. And I wonder what am I missing. Please help. Many thanks in advance.

Related

How to create in mongoose, if it exists, update it in mongoose

I have problem when I want create new model or if not exist, update it.
For example, I have data in a database:
{
"unix": 1668380400,
"type": "soup",
"order": 1,
"value": "Chicken"
},
{
"unix": 1668380400,
"type": "main",
"order": 0,
"value": "Gulash"
},
{
"unix": 1668553200,
"type": "soup",
"order": 0,
"value": "Asian"
}
}
I want to get to the point that when unix and type and order are the same - modify the value. But if the element with the same unix, order and type is not found in the database - add a completely new record to the db.
I thought this was how I would achieve the desired state. But a mistake.
router.post("/add", async (req, res) => {
const data = req.body;
await data.map((el) => {
const { unix, type, order, value } = el;
Menu.findOneAndUpdate(
{ unix, type, order },
{ unix, type, order, value },
{ new: true, upsert: true }
);
});
res.status(201).json({ status: true });
});
req.body:
[
{
"unix": 1668380400,
"type": "main",
"order": 2,
"value": "Sushi"
},
{
"unix": 1668553200,
"type": "soup",
"order": 0,
"value": "Thai"
}
]
Thanks for any help.
I think I found a solution. Everything works as it should, but wouldn't it be better to send the data with JSON.stringify() and then parse this data on the servers using JSON.parse()?
Another thing is the map method. Is it OK like this? Can't cause throttling?
router.post("/add", (req, res) => {
const data = req.body;
data.map(async (el) => {
const { unix, type, order, value } = el;
await Menu.findOneAndUpdate(
{ unix, type, order },
{ value },
{ upsert: true }
);
});
res.status(201).json({ status: true });
});

What is the correct way to hit the API in GetX?

I am using Getx GetConnect() to hit the API. But most of the time GetConnect() is not hitting the API. I am not sure what is going wrong.
This is my code :
Response response = await GetConnect().post(
apiBaseUrl + taskPathApi + getV2,
{
"query": {
"tasker_id": kTaskerId,
"task_status": [13],
"tasker_availability": ["Checking", "Yes", "No"]
},
"display": {
"perpage": 3,
"pageno": pageNumber,
"sorting_task": "start_asc"
},
},
headers: {
"accept-language": kLanguageCode.value,
},
);
if (response.statusCode == 200) {
status = TaskList.fromJson(response.body).status;
if (status) {
totalCount = TaskList.fromJson(response.body).data.count;
taskList.addAll(TaskList.fromJson(response.body).data.tasks);
pageLoading = false.obs;
refreshRequestedTask.loadComplete();
update();
}
} else {
print("Something went wrong");
refreshRequestedTask.loadComplete();
}
Is this the proper way to use GetConnect() ? or I am doing something wrong ?
Here is the full example of GetX API call example
https://github.com/dhola-hardik/flutter_getx_example.git

How to populate array of objects in mongoose

I have this code -
const getAllCourses = async (req, res) => {
const courses = await Course.find({});
try {
await courses.populate('professor')
res.send({ status: 200, data: { courses } });
} catch (err) {
res.status(500).send({ status: 500, message: "Internal server error." });
}
};
Also, this is the response I'm getting from postman -
{
"status": 200,
"data": {
"courses": [
{
"_id": "61dc47f58f88c1a7e9bd36b6",
"name": "Course1",
"professor": "61dc1299431cd669faad7d0f",
"students": [
{
"student": "61dc0b7f103b531f105e8e4c",
"_id": "61dc47f58f88c1a7e9bd36b7"
},
{
"student": "61dc220885886a9f1d8e94d0",
"_id": "61dc47f58f88c1a7e9bd36b8"
}
],
"createdAt": "2022-01-10T14:51:33.313Z",
"updatedAt": "2022-01-10T14:51:33.313Z",
"__v": 0
},
{
"_id": "61dc47fb8f88c1a7e9bd36bf",
"name": "Course2",
"professor": "61dc1299431cd669faad7d0f",
"students": [
{
"student": "61dc0b7f103b531f105e8e4c",
"_id": "61dc47fb8f88c1a7e9bd36c0"
},
{
"student": "61dc220885886a9f1d8e94d0",
"_id": "61dc47fb8f88c1a7e9bd36c1"
}
],
"createdAt": "2022-01-10T14:51:39.704Z",
"updatedAt": "2022-01-10T14:51:39.704Z",
"__v": 0
}
]
}
}
Now what I'm trying to do is to populate the professor and the students but it doesn't seem to work.
I tried populating "courses.professor", "course.professor", "professor" but nothing worked for me.
What am I missing?
Here is an example of how this can be done for a document with an array friends on it:
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
});
I just solved it by chaining the populate method directly after the Course.find({}) and it just worked, I'm not sure why though.
Solution:
const getAllCourses = async (req, res) => {
const courses = await Course.find({}).populate('professor').populate('students.student');
try {
res.send({ status: 200, data: { courses } });
} catch (err) {
res.status(500).send({ status: 500, message: err.message });
}
};

How to return the a formatted response from a mongo query/projection?

I'm trying to create an API to validate a promocode. I have minimal experience with mongo and the backend in general so I'm a bit confused in what is the best approach to do what I'm trying to accomplish.
I have this PromoCode form in the client. When a user types a promocode I would like for my backend to
verify if the code exists in one of the docs.
if it exists then return that code, the value for that code and the couponId
if the code doesn't exist then return an error.
My db is structured like this. The user will type one of those codes inside the codes: []
{
"_id": {
"$oid": "603f7a3b52e0233dd23bef79"
},
"couponId": "rate50",
"value": 50,
"codes": ["K3D01XJ50", "2PACYFN50", "COKRHEQ50"]
},
{
"_id": {
"$oid": "603f799d52e0233dd23bef78"
},
"couponId": "rate100",
"value": 100,
"codes": ["rdJ2ZMF100", "GKAAYLP100", "B9QZILN100"]
}
My route is structure like this:
router.post('/promoCode', (req, res, next) => {
const { promoCode } = req.body;
console.log('this is the req.body.promoCode on /promoCode', promoCode)
if (!promoCode) {
throw new Error('A promoCode needs to be passed')
}
promoCodesModel
.validatePromoCode(req.body.promoCode)
.then((response) => {
console.log('response inside /promoCode', response)
res.status(200).json({ data: response })
})
.catch((error) => {
res.status(400).json({ result: 'nok', error: error })
})
})
The validatePromoCode function is the following:
const validatePromoCode = async (code) => {
try {
let promoCode = await PromoCodesModel.find(
{"codes": code},
{_id: 0, codes: { $elemMatch: { $eq: code }} })
console.log('This is the promocode', promoCode)
return promoCode
} catch (err) {
throw new Error (err.stack)
}
}
All this seems to sort of work since I get the following response when the code is typed correctly
{
"data": [
{
"codes": [
"COKRHEQ50"
]
}
]
}
when typed incorrectly I get
{
"data": []
}
What I would like to get back is. (How can I accomplish this ?). Thanks
// when typed correctly
{
"data": { value: 50, couponId: "rate50", code: "COKRHEQ50" }
}
// when typed incorrectly
{
"error": "this is not valid code"
}
TL;DR: I would like to return a formatted query with specific values from a mongo query or an error object if that value does not exist on the document object.
Ok just figured it out
To be able to get the this responsed (what I wanted):
{
"data": [
{
"codes": [
"K3D01XJ50"
],
"couponId": "rate50",
"value": 50
}
]
}
I ended up having to do this on validatePromoCode
onst validatePromoCode = async (code) => {
try {
let promoCode = await PromoCodesModel.find(
{ codes: code },
{ _id: 0, codes: { $elemMatch: { $eq: code } }, couponId: 1, value: 1 },
)
return promoCode
} catch (err) {
throw new Error(err.stack)
}
}
But is there a better way on doing this ? Thanks

Update single specific field only when using $ in embedded document Mongodb

Here's my snippet of code.
router.post(
"/chapter/officers/edit/:id/:c_id",
async (req, res) => {
try {
const updateChapter = await Council.findOneAndUpdate(
{ "chapters._id": req.params.c_id },
{
"chapters.$.officers": req.body,
}
);
if (!updateChapter) return res.status(404).json({ msg: "Not found" });
res.json("Edit Success");
} catch (error) {
res.status(500).json({ msg: error.message });
}
}
);
I am planning on updating only one specific field at a time BUT when I tried to send this JSON from Postman
{
"grandTriskelion": "sample"
}
The other filled in field values becomes an empty string. Heres an example of my res.json
"_id": "5fc9cbb7ba7e2e2430c9a4d8",
"name": "Maria Aurora",
"code": "MA",
"chapters": [
{
"officers": {
"grandTriskelion": "sample",
"deputyGrandTriskelion": "",
"masterWilderOfTheWhip": ""
},
"_id": "5fca014e49fa3f2910794bb8",
"name": "Maria Aurora Community Based"
}
],
I've hit a roadblock. I'm a beginner at MERN stack.