hapi single page application using inert plugin doesn't serve up api route - hapi.js

I am trying to build a single page application using hapi and inert.
my example code is here: https://github.com/7seven7lst/hapi-inert-test
and the base of the project is built from the answer here nodejs hapi single page
Basically I would like to both server static file and api json data to front end. I know how to do this in express, but haven't figure out how with hapi. the delimma is : if I use hapi only, it doesn't serve up static file, and if i use hapi+inert, it wont' serve up api route.
solutions????

The documentation says that the route handler chooses the route from most specific to least specific. So you can pre-fix your api routes with something like /api/v1/ and then everything else that doesn't begin with /api/v1/ will get routed to static files dished up by inert.
Hapi.js Routing Documentation:
When determining what handler to use for a particular request, hapi searches paths in order from most specific to least specific. That means if you have two routes, one with the path /filename.jpg and a second route /filename.{ext} a request to /filename.jpg will match the first route, and not the second. This also means that a route with the path /{files*} will be the last route tested, and will only match if all other routes fail.
'use strict'
const Hapi= require('Hapi')
// Config
var config= {
connection: {port: 3000, host: 'localhost'}
}
const server= new Hapi.Server()
server.connection(config.connection)
const plugins= [
// https://github.com/hapijs/inert
{ register: require('inert'), options: {} },
]
function setupRoutes() {
// Sample API Route
server.route({
method: 'GET',
path: '/api/v1/Person/{name}',
handler: function (req, reply) {
reply('Hello, '+ encodeURIComponent(req.params.name)+ '!')
}
})
// Web Server Route
server.route({
method: 'GET',
path: '/{files*}',
// https://github.com/hapijs/inert#the-directory-handler
handler: {directory: {path: '../html_root', listing: false, index: true } }
})
}
server.register(plugins, (err)=> {
if (err) {throw err}
// Initialize all routes
setupRoutes()
// Start the Server
server.start((err)=> {
if (err) {throw err}
server.log('info', `Server running at: ${server.info.uri}`)
})
})

Related

Strapi v4 Extending Server API for Plugins does not work

I am trying to follow the Strapi v4.0.0 guide on https://docs.strapi.io/developer-docs/latest/developer-resources/plugin-api-reference/server.html#entry-file for extending the users-permission plugin to add a custom route/controller, but so far have been unsuccessful. I add the custom files as stated in the docs, but there is no change in the UI.
I managed to get this to work for normal API highlighted in yellow, but was unable to do so for the users-permission plugin
In the previous version 3.6.8 this functionality was allowed through the extensions folder.
Am I missing something from the new guide, I even tried copying the files from node_modules > #strapi > plugin-users-permission and adding a new route and method to the exiting controller file but it still does not reflect the change in the section where we assign different route permission to roles. The user-permission plugin still shows the original routes, with no change.
Thanks,
I ran into this thread while researching pretty much the same issue, and I wanted to share my solution.
First of all, I found this portion of the documentation more useful than the one you referenced: https://docs.strapi.io/developer-docs/latest/development/plugins-extension.html
My goal was the write a new route to validate JWT tokens based on the comment made here: https://github.com/strapi/strapi/issues/3601#issuecomment-510810027 but updated for Strapi v4.
The solution turned out to be simple:
Create a new folder structure: ./src/extensions/user-permissions if it does not exist.
Create a new file ./src/extensions/user-permissions/strapi-server.js if it does not exist.
Add the following to the file:
module.exports = (plugin) => {
plugin.controllers.<controller>['<new method>'] = async (ctx) => {
// custom logic here
}
plugin.routes['content-api'].routes.push({
method: '<method>',
path: '/your/path',
handler: '<controller>.<new method>',
config: {
policies: [],
prefix: '',
},
});
return plugin;
};
If you're unsure what controllers are available, you can always check the API documentation or console.log(plugin) or console.log(plugin.controllers).
After the admin server restarts, you should see your new route under the user-permissions section as you would expect, and you can assign rights to it as you see fit.
My full strapi-server.js file including the logic to validate JWT:
module.exports = (plugin) => {
plugin.controllers.auth['tokenDecrypt'] = async (ctx) => {
// get token from the POST request
const {token} = ctx.request.body;
// check token requirement
if (!token) {
return ctx.badRequest('`token` param is missing')
}
try {
// decrypt the jwt
const obj = await strapi.plugin('users-permissions').service('jwt').verify(token);
// send the decrypted object
return obj;
} catch (err) {
// if the token is not a valid token it will throw and error
return ctx.badRequest(err.toString());
}
}
plugin.routes['content-api'].routes.push({
method: 'POST',
path: '/token/validation',
handler: 'auth.tokenDecrypt',
config: {
policies: [],
prefix: '',
},
});
return plugin;
};
When exporting routes you need to export the type, either content-api or admin. Look at the Strapi email plugin in node_modules for example, change the folder and file structure in your routes folder to match that and then you will be able to set permissions in the admin panel.
If your Strapi server is using Typescript, make sure that you name your extension files accordingly. So instead of strapi-server.js, you would need to name your file strapi-server.ts.

Nuxt.js env Property, understanding and how to use it?

following https://nuxtjs.org/api/configuration-env
I have been trying to set up my apiUrl in nuxt.config.js once for the whole project, like:
export default {
env: {
apiUrl: process.env.MY_REMOTE_CMS_API_URL || 'http://localhost:1337'
}
}
adding this in nuxt.config.js, I'd expect (and would like) to have apiUrl accessible everywhere in the project.
In particular, it is needed for the 3 following cases:
with axios, to generate static pages from dynamic urls (in nuxt.config.js)
generate: {
routes: function () {
return axios.get(apiUrl + '/posts')
.then((res) => {
return res.data.filter(page => {
return page.publish === true;
}).map(page => {
return {
route: '/news/' + page.slug
}
})
})
}
},
with apollo, to get data via graphql (in nuxt.config.js)
apollo: {
clientConfigs: {
default: {
httpEndpoint: apiUrl + '/graphql'
}
}
},
in every layout, page and components, as the base url of media:
<img :src="apiUrl + item.image.url" />
As you might see, only thing I need is to 'print' the actual base url of the cms.
I have also tried to access it with process.env.apiUrl, with no success.
The only way I was able to make it has been to create an extra plugin/apiUrl.js file, which injects the api url, and seems wrong to me as I am now setting the apiUrl twice in my project.
I asked this question in the past, but in a way less clear way. I was suggested to use dotenv, but from the docs it looks like adding an additional layer of complication that might not be necessary for a simpler setup.
Thanks.
I think dotenv module really is what you need.
This is my setup:
Project root has a .env file that contains
BASE_URL=https://www.myapi.com
require('dotenv').config() at top of nuxt.config.js
#nuxtjs/dotenv installed and added to buildModules of nuxt.config.js
env: { BASE_URL: process.env.BASE_URL} added to nuxt.config.js
axios: { baseURL: process.env.BASE_URL } added to nuxt.config.js (optional)
You should have access to your .env throughout the project. (process.env.BASE_URL)
I haven't used apollo, but you should be able to set the apollo endpoint with process.env.BASE_URL + '/graphql'
As of Nuxt 2.13, #nuxtjs/dotenv is not required anymore. Read here
The concept that I was missing is that you set up the same named variable in your server / pipeline, so that you have your (always local / never pushed) .env file and a same name variable remotely, not added to your repo (where the value can be the same or different)

Feedly API with NuxtJS Axios

I am trying to access the Feedly API via my nuxtjs site. To do so, I am using the nuxt-axios module.
To get started, I take note of the Feedly API instructions:
We offer a standard OAuth 2.0 authentication module which provide the application an OAuth access token. Most endpoints expect an Authorization header.
$ curl -H 'Authorization: OAuth [your developer access token]' https://cloud.feedly.com/v3/profile
I now attempt to integrate this into nuxtjs-axios.
First, I set up my nuxt-config.js file:
export default {
...
plugins: [{ src: `~/plugins/axios.js` }],
modules: [
'#nuxtjs/axios',
],
axios: {
credentials: true
},
env: {
FEEDLY_ACCESS_TOKEN:
[MY_FEEDLY_DEV_ACCESS_TOKEN]
},
...
}
I then create a axios.js plugin in the plugins folder (which is imported into the nuxt-config.js file that I noted above):
export default function({ $axios }) {
$axios.setHeader('Authorization', `OAuth ${process.env.FEEDLY_ACCESS_TOKEN}`)
}
The problem is that I have no idea what I'm supposed to put in the axios.js plugin file --- or even if that is the right way to do this. What I did is really just a stab in the dark.
So my question is, how can I implement the Feedly API into nuxtjs using the nuxtjs-axios module?
Thanks.
Use interceptor:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
https://github.com/axios/axios/blob/master/README.md#interceptors
What I've understood of the nuxt-axios documentation is that the plugin.axios file is used for adding "default" behavior (axios helpers: https://axios.nuxtjs.org/helpers/)
I think that you've got the plugin right (if the token is the only thing you need to add to your header).
With the nuxt-axios enabled you can now use the this.$axios.get/post.
Have you tried to run a component with:
this.$axios.get('**feedly_url_api_url_here**').then(response)....

Logging in HapiJS v16 Models

I've created a HapiJS project, using my own MVC pattern.
When I want to log from inside my controllers in some cases. Currently when I want to log from my controllers I simply invoke request.log. I'm using Good as a logging plugin.
For example:
const user = function(req, res){
// do stuff
req.log(['info'], 'some log info here');
};
module.exports = {
user,
};
How can I log from inside my models where I have no request object? I don't want to have to pass in my request object into the methods of the model.
If you plan to register models as plug in, you will have access to the server object and so, you will be able to use server.methods
EDIT
In my company we declare routes as plug in (see code below)
exports.register = function (server, options, next) {
server.route({
method: 'POST',
path: '/FOO/BAR'
handler(request, reply) {}
});
return next();
};
exports.register.attributes = {
name: 'routes-foobar'
};
And we register as such :
server.register([
require('./route-foo-bar'),
...,
]);
This way we have the server objects in our route
What I would do in your case is register my models as server methods and use them in my routes.
The same goes for logging.
I would register my log function as a server method and call them from inside my models
I don't know if it's the good way to do that but that's a least a working one

Where is the unresolved path of a Hapi Request?

Given this route config:
server.route
method: 'GET'
path: "/app/usage/{id}"
handler: (req, reply) ->
...
Is there a way to programmatically get the unresolved path /app/usage/{id} from the request object in a prehandler? I know how to get the resolved path e.g. /app/usage/1234, but I would like the unresolved path (ideally without having to reconstruct it with string manipulation).
server.ext 'onPreHandler', (request, reply) ->
resolvedPath = request.path
unresolvedPath = ?
By "unresolved path", I'll presume you mean the path option specified when creating a route using server.route(options)?
The entry from the routing table for the route that gets matched to a request is placed in request.route for your inspection:
server.route({
method: 'GET',
path: '/app/usage/{id}',
handler: function (request, reply) {
const route = request.route;
const routePath = route.path; // '/app/usage/{id}'
reply('hello')
}
});
It's available throughout the request lifecycle, so you can fetch it in an onPreHandler extension function too:
server.ext('onPreHandler', function (request, reply) {
const route = request.route;
const routePath = route.path; // Whatever your route path is for the request
reply.continue();
});
NOTE Be aware that you can't view request.route.path inside an onRequest extension function, because this is called before a route is matched. From the relevant section in the API docs:
onRequest extension point
request.route is not yet populated at this point.
Lookup route using request path
...