How to change base url from $fetch in Nuxt3? - nuxtjs3

In nuxt 2 we could do something like:
nuxt.config.js
...
axios : {
baseURL: 'some url'
}
what is the equivalent to that in nuxt3 for $fetch?

Related

getting error when using nuxt 3 with nuxt auth module

I am using nuxt 3 + nuxt auth module
getting this error :
this is my nuxt config
export default defineNuxtConfig({
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next'
],
auth: {
strategies: {
cookie: {
cookie: {
// (optional) If set, we check this cookie existence for loggedIn check
name: 'XSRF-TOKEN',
},
endpoints: {
// (optional) If set, we send a get request to this endpoint before login
csrf: {
url: ''
}
}
},
}
}
})
what is the problem ?
The auth module is currently not supported by Nuxt3 but it is planned on the roadmap.
https://v3.nuxtjs.org/community/roadmap#%EF%B8%8F-roadmap
Latest official update: https://twitter.com/Atinux/status/1570317156033642496?t=YNN0iWL6M5l3Z0xm_ernCg&s=19

Nextjs: How to send a custom 200 response at root when the base path is configured

I m using nextjs and have configured base path in next.config.js.
It looks something like this
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
basePath: '/new',
};
So now whenever I hit http://localhost:3000/new I get the homepage.
Howevever, when I hit http://localhost:3000 without basePath, I get a 404.
What I want is to get a 200 response with some custom response like OK.
Even if I don't get the custom response text, getting 200 is required.
How to achieve that?
First do this
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
basePath: '/new',
};
Just as you have done already, to the next thing you have to do is to add a middleware just at the root of the page
Then watch for the pathnames that is passed from the request
export async function middleware(req: NextRequest) {
const { nextUrl} = req;
if(nextUrl.pathname === '/'){
return NextResponse.json({hello: "world" });
}
}

Why is my nextjs router not return query params?

When I navigate to http://localhost:3000/users/123?foo=bar of my nextjs app
I get the following when I print out router.query
{id: "123"}
What could be the reasons it is not adding foo: 'bar' to the query object?
Your file layout should look like this:
pages/
users/
[id].js
Having just tested this, the returned query object is {"foo":"bar","id":"123"}.
I had to add a next.config.js file with the following
module.exports = {
reactStrictMode: true,
async rewrites() {
return [
{
source: '/pages/:slug*',
destination: '/:slug*'
}
]
}
}

Unable to connect woocommerce rest api with angular 4

I am trying to connect my woocommerce rest api with angular 4 to fetch product list in my ionic 3 project but every time url throw 404 not found errror i am not able to understand what i am doing wrong
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
WooCommerce: any;
constructor(public navCtrl: NavController) {
this.WooCommerce = WC({
url: "http://localhost:8100/wordpress/wp-json/",
consumerKey: "ck_4d99b09e85e45a11282fe2150945fc2090eea0f0",
consumerSecret: "cs_3acf2c3eeb334ab84309e890a5070f8509de9201"
});
this.WooCommerce.getAsync("products").then( (data) => {
console.log(data);
}, (err) => {
console.log(err);
});
}
}
First thing Santosh you should always avoid using your private keys while asking questions , just mention like i did.
i am using this api currently in my app and faced the same issue, try using the exact same url which you use to open the site locally.
i think changing your url to just "http://localhost:8100/wordpress/" should work
this.WooCommerce = WC({
url: "http://localhost:8100/wordpress/",
consumerKey: "your consumer key",
consumerSecret: "your consumer secret"
});
or else in my case i just passed version along it and it worked, you can check by passing both wpApi and version and hopefully that works
this.WooCommerce = WC({
url: "http://localhost:8100/wordpress/",
consumerKey: "your consumer key",
consumerSecret: "your consumer secret",
wpAPI: true,
version: 'v3'
});
I was also facing this issue but now i got the solution.
Just add these lines in .htaccess file that is in your woocommerce folder.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
And set the url in home.ts like
url: "http://localhost:8100/wordpress/",
instead of
url: "http://localhost:8100/wordpress/wp-json/",

Async load routes data and build route instruction for Angular 2

I try to build dynamically routes from angular2 (fetch route config from server), after that I parse it and generate instruction for component route (I have parent routes config and child into different components, because I don`t know how define route for child component into one main.app.ts file).
The problem is when app started and try to create routes config and routeGenerator is not build routes yet (async delay) cant parse routes data (because async delay, so routesData undefined now) and app is crashig. I dont know what to do with this. Looking for lifecycle hood (some like - #Angular2BeforeAppStarted ) but found nothing.
import {Component, Input, OnChanges} from 'angular2/core';
import {RouteConfig, RouterOutlet, ROUTER_DIRECTIVES, Router} from 'angular2/router';
/* ------- !Angular 2 native components ---------*/
import {routeGenInstance} from '../../config/routes/patient_routes';
protected const BUILT_MODULE_PATH: string = '/built/modules/patients/';
#Component({
template: `
<router-outlet ></router-outlet>
`,
directives: [RouterOutlet, ROUTER_DIRECTIVES]
})
#RouteConfig(routeGenInstance.getRouteDefinitions())
export class PatientsComponent {
#Input();
constructor() {}
}
Also i try to update routes in the same way (but app is crashed immediately because my Navigation link in navigation component is not have some correct link way)
import {RouteConfig, RouterOutlet, ROUTER_DIRECTIVES, Router} from 'angular2/router';
constructor(
private router: Router
) {
router.config([
routeGenInstance.getRoutesDefinition()
])
}
my route definitions use Async loader so they are correct and work whithout async delay. I don`t know how to make angular wait for my routes definitions and thet start to run the app.
Please, help me. Thanks.
UPD:
#Thierry many thanks for your help again. You are awesome my friend and mentor. One last question (last). Can you tell me how I can define routeConfig into one app file with child subrouting definition?
Its mean. I have main level routes into app files
{
path: '/',
name: 'Dashboard',
component: DashboardComponent,
useAsDefault: true
},
{
path: '/patients/...',
name: 'Patients',
component: PatientsComponent
},
and patient sub routes into patientsComponent (#RouteConfig)
{
path: '/', // root is appRoot/patients/...
name: 'PatientsList', component...},
{
"name": "Chart",
"path": "/chart/:id", component...
},
How to define this route config only into one app.file ? (How to configure route with sub routing in one file)?
An option could be to get your configuration before bootstrapping your application.
var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);
http.get('routes.json').map(res => res.json())
.subscribe(data => {
bootstrap(AppComponent, [
HTTP_PROVIDERS
provide('routesConfig', { useValue: data })
]);
});
Then you can have access the routes configuration by dependency injection and in a synchronous way:
#Component({
(...)
})
export class AppComponent {
constructor(#Inject('routesConfig') private routesConfig, private router:Router) {
// Configure here your routes
}
}
These two questions could help you:
How to bootstrap an Angular 2 application asynchronously
angular2 bootstrap with data from ajax call(s)
Edit
You can leverage the Observable.forkJoin method to load your route configuration from different requests:
var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);
Observable.forkJoin([
http.get('mainRoutes.json'),
http.get('childRoutes.json')
])
.map(responses => {
return {
main: res[0].json(),
children: res[1].json()
};
})
.subscribe(data => {
bootstrap(AppComponent, [
HTTP_PROVIDERS
provide('routesConfig', { useValue: data })
]);
});
Edit1
I think that you could try something like that:
[
{
path: '/patients/...',
name: 'Patients',
component: PatientsComponent,
childRoutes: [
{
path: '/', // root is appRoot/patients/...
name: 'PatientsList', component...
},
(...)
]
}
]
But you need to split the content to get different elements according to the hints you want to handle:
one for the root:
[
{
path: '/patients/...',
name: 'Patients',
component: PatientsComponent
}
]
several for children. For example for patients:
[
{
path: '/', // root is appRoot/patients/...
name: 'PatientsList', component...
},
(...)
]
In the new router (>= RC.3) https://angular.io/docs/js/latest/api/router/index/Router-class.html#!#resetConfig-anchor resetConfig can be used
router.resetConfig([
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'simple', component: SimpleCmp },
{ path: 'user/:name', component: UserCmp }
] }
]);
See also https://github.com/angular/angular/issues/9472#issuecomment-229230093
You can load components asynchronously by providing a SystemJsComponentResolver.
Right now, you can load routes asynchronously and imperatively update the configuration using resetConfig.
Once AppModules are in master, we will utilize those to implement async loading of subconfigs.
https://github.com/angular/angular/issues/11437#issuecomment-245995186 provides an RC.6 Plunker
Check this:
DynamicalAsyncRouter
https://github.com/Longfld/DynamicalAsyncRouter
Using Observables/Promises to provide route translations is not a reliable solution, hence the Angular router expects Route[] or Routes, but an HTTP request can only return an Observable/Promise.
The Angular app gets initialized, but the retrieval process of route translations still goes on using Observables/Promises.
As Thierry Templier said, to get your configuration before bootstrapping your application would solve the problem.
Also, check the #ngx-i18n-router/core on github.

Resources