The API call doesn't append properly in NextJS - next.js

Folder structure
-Pages
--Support
---StaffTable.js
await axios.post('api/updateStaffDetails', { data: dataToSubmit });
What I try: I once encountered this issue this is my previous solution, I just add '/' infront of the API call but this time it doesn't work
await axios.post('/api/updateStaffDetails', { data: dataToSubmit });
My thoughts: It seems like nextJS 'glued' the first name of the page into any API call made in that page in this case a nested static route /support/StaffTable the first name is support.
Actual: /localhost/support/updateUser
Expected: /localhost/api/updateUser
Much help or guide or is much much much appreciated . Thank you , have a good day

This should work -
await axios.post('/api/updateStaffDetails', { data: dataToSubmit });
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. So axois request to '/api/updateStaffDetails' will call the handler(export a function as default) written in pages/api/updateStaffDetails.js

Related

What is the difference between axios and useFetch (nuxt 3)?

I'm slowly starting to migrate from nuxt 2 to nuxt 3.
Previously I used to use axios.
In Nuxt3, it is recommended to use useFetch
However the behavior is quite weird with useFetch. Calls are not made systematically.
For example in this piece of code :
async mounted() {
const store = useAuth();
let response = await axios.get('http://dev.test.fr/api/secured/admin', {headers : store.authHeader() });
this.sensibleInformation = response.data;
},
With Axios, every time I open this page, the call is made and the sensibleInformation is up to date.
With useFetch, the syntax is similar
async mounted() {
const store = useAuth();
let response = await useFetch('http://dev.malt.fr/api/secured/admin' , {method : 'get', headers : store.authHeader() });
this.sensibleInformation = response.data;
},
But the call to the server is done... sometimes. So, the sensibleInformation is most of the time empty. And I don't find any explanation in the documentation.
Maybe there is something I miss here.
I'm using nuxt 3.0.0-rc.6
As it is explained in nuxtJS3 useFetch
useFetch is a wrapper for $fetch(come from here ohmyfetch)
you don't need to import this lib it is include in vuejs3 and lastly axios was not compatible with vuejs3 explained here why use $fetch
what is really great is that body is automatically parsed in JSON, so no need to parse or stringify anything. Also header for content type is automatically added.
So no need to import any library, automatic parsing, automatic header detected etc...
Not sure about this one, but I think the "useFetch" helper is designed to be used with the Vue composition API, so :
within the "setup" function
directly in your script tag if you're using the "<script setup>" synthax
The issue you are dealing with maybe due to the fact that you're using "useFetch" within the "mounted" hook of Vue.js options API.
But once again, not sure about this one :)
The major difference between useFetch and Axios is that useFetch is a wrapper around useAsyncData (and native $fetch) and so works with both SSR and Static modes of Nuxt.
If using it in the onMounted hook you will probably get more expected results if you set the server option to false so it runs only in the client (more like how Axios runs in the mounted hook). I have predominantly used it in <script setup> for SSR set ups.
More info here: https://v3.nuxtjs.org/api/composables/use-fetch

In Postman, how to define pm.iterationData() when NOT using Collection Runner?

My use case is simple: I have a Postman Collection with a few requests, one of them is:
GET www.example.com/stores?country={{country}}
Then a simple Test:
pm.test("Check number of stores", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.stores.length).to.equal(pm.iterationData.get("size"));
});
So everything is nice and merry with the following Collection data used in the Collection Runner:
country,size
UK,15
US,32
However when I simply want to run this via the main Postman window, obviously the request and the Test fails. I can set a collection variable country to SE, but I have no idea how to set size in pm.iterationData just to try if my request and test script is working fine for another "country" - without running the whole collection/iterations.
Thanks in advance for all the help!
I'm not sure if you can modify iteration data variable in runtime, but a workaround for this issue is to copy your request from the original folder into a new folder, then you can run the whole folder with only one request, you dun have then to run all the requests within the collection.

Allow access to web application only when my server redirects to it

My question is very very similar to this one
The idea is the following.
I have an app written in Node (specifically Sails.js) it a simple form for invoices.
And another one in Laravel.
So what I want is that the user can only access that form (Sails app) if one Controller of the Laravel app redirects to it.
On the link above it says that I could use sessions but as you can see this are very different applications. So I'm looking for the simplest and best way to do it.
Any advice is well received or if you have some better approach to solve this please let me know. Thanks
Probably the most simple way is to use the referer header in your Sails controller and do a simple comparison check.
For example:
getinvoice : function(req, res, next) {
var referer = req.headers.referer;
if(referer != 'http://somedomain.com/pageallowedtocallgetinvoice'){
return res.forbidden();
} else {
...
}
}

Previous page location on IronRouter

Is there a way to get the previous page location before going to the next page in IronRouter?
Is there an event I can use to fetch this information?
Thanks in advance.
Since Iron Router uses the usual History API, you can just use the plain JS method:
history.go(-1);
or
history.back();
Edit: or to check the previous path without following it:
document.referrer;
You can achieve the behavior you want by using hooks.
// onStop hook is executed whenever we LEAVE a route
Router.onStop(function(){
// register the previous route location in a session variable
Session.set("previousLocationPath",this.location.path);
});
// onBeforeAction is executed before actually going to a new route
Router.onBeforeAction(function(){
// fetch the previous route
var previousLocationPath=Session.get("previousLocationPath");
// if we're coming from the home route, redirect to contact
// this is silly, just an example
if(previousLocationPath=="/"){
this.redirect("contact");
}
// else continue to the regular route we were heading to
this.next();
});
EDIT : this is using iron:router#1.0.0-pre1
Apologies for bumping an old thread but good to keep these things up to date saimeunt's answer above is now deprecated as this.location.path no longer exists in Iron Router so should resemble something like the below:
Router.onStop(function(){
Session.set("previousLocationPath",this.originalUrl || this.url);
});
Or if you have session JSON installed (see Session JSON)
Router.onStop(function(){
Session.setJSON("previousLocationPath",{originalUrl:this.originalUrl, params:{hash:this.params.hash, query:this.params.query}});
});
Only caveats with thisis that first page will always populate url fields (this.url and this.originalUrl there seems to be no difference between them) with full url (http://...) whilst every subsequent page only logs the relative domain i.e. /home without the root url unsure if this is intended behaviour or not from IR but it is currently a helpful way of determining if this was a first page load or not

Using Meteor, is it possible to have "dynamic routes?"

sorry, I'm new to webdev and Meteor and I'm not quite sure of the correct terminology. I am using Meteor-Router to create routes in my Meteor app.
I'm trying to create a test restaurant app, so an entry in my database might be:
name: "Kentucky Fried Chicken"
type: "Fast Food"
On the main page of the app, you see a list of restaurants. But the user can click on any item on that list to get to a more detailed page.
I would rather that the urls don't look like:
/restaurant/123
but more so like:
/fast-food/kentucky-fried-chicken
/japanese/sushi-r-us
/italian/some-italian-restaurant-name
Is this possible to do with Meteor & Meteor-Router? Thank you!
Btw, right now my routes are very simple:
Meteor.Router.add({
'/': 'home',
'/admin': 'admin',
'/403': 'unauthorized'
});
You can use more complex routes than the one you're using now, like this:
Meteor.Router.add({
'/:type/:restaurant': function(type, restaurantName) {
var restaurant = Retaurants.findOne({type: type, name: restaurantName});
Session.set('restaurantFromUrl', restaurant);
// Now your restaurant is in the "restaurantFromUrl" Session
return 'restaurantPage';
}
});
The /:type and /:restaurant will be passed into the callback and be whatever you set them to in your URL. Oh, and you might want to add a /show-restaurant/type/name/ also, else all urls (that aren't set up in other routes) that match the patter "/whatever/url" will try to get a restaurant.
Everything you need to know is here: https://github.com/tmeasday/meteor-router
Oh, and this is just an example. Haven't tested it but it should work.
Current route package for Meteor that most people use is: Iron Router

Resources