Example using /rs/cors as preware with Buffalo? - go

I'm trying to get the /rs/cors package to work with the latest Buffalo as Preware, which is supposed to work according to a recent blog post (https://blog.gobuffalo.io/buffalo-v0-9-4-released-5d2327a4742e), but the code snippet there doesn't seem to make sense. If I generate a new buffalo app as an API, and I look at adding the cors package, I start with:
app = buffalo.New(buffalo.Options{
Env: ENV,
SessionStore: sessions.Null{},
SessionName: "_creatorhub_session",
})
// Automatically redirect to SSL
app.Use(ssl.ForceSSL(secure.Options{
SSLRedirect: ENV == "production",
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
}))
// Set the request content type to JSON
app.Use(middleware.SetContentType("application/json"))
I should obviously add something along the lines of "PreWares: []buffalo.PreWare{}," but it seems to want a HandlerFunc, which /rs/cors doesn't seem to return under normal use, so I'm failing to find the right combination to make these work properly together and I haven't found a working example.
Anyone out there have an example to share? Any ideas appreciated!

Finally figured it out, so I'll share the info here for anyone else. This is using Buffalo v0.10.1 and the https://github.com/rs/cors project. I dug in and found that I could set up the cors object with (using localhost for example):
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:8080"},
AllowCredentials: true,
})
and then add it into the Buffalo instantiation by getting the Handler out of it:
app = buffalo.New(buffalo.Options{
Env: ENV,
SessionStore: sessions.Null{},
SessionName: "_creatorhub_session",
PreWares: []buffalo.PreWare{c.Handler},
})
That worked for me. The issue was that it was difficult to find documentation for what Buffalo wanted passed in to PreWare and matching it up with what could be provided by the cors package.
Hope this helps out someone else in the future!

Related

slash command "dispatch_failed"

I have went through creating the custom slash command configuration via slack and installed it on workspace. However when I run it I get this
/testing failed with the error "dispatch_failed"
I tried multiple workspaces but same issue. Anyone experienced this?
So after a few tests, I found out that this is just a generic message of anything that fails at slack at this point. I have first my endpoint that was unreachable. So it was returning this message. I fixed that, used ngrok for tunnel so that I could debug and that is how I found this issue.
Also, this error can occur due to the following reasons as well.
Errors in code
Unreachable backend or Invalidly configured slash command in the app
While the documentation tells you:
"use the Request URL is your base server link + "/slashcommand" after it"
This is incorrect. The request URL should be: "/slack/events"
Of course the command needs to match whats in the 'edit command' window and in the method '.command' in your app.js:
app.command('/flash-card', async ({ ack, body, client })
If you're using ngrok http <port> to test in your localhost, be aware that a new ngrok public URL is created every time you run this command. So in https://api.slack.com/apps, in your app's Features, you may have to update your Slash Command' request URL with the current ngrok URL generated for you.
You need to set the Method in the Integration Settings to GET, is default to POST
This is also the error for a 404 Not Found.
If you're developing offline with ngrok, the 404 error can be seen in the terminal.
If you're deploying with serverless, ensure that you're handling the new endpoint /slack/command. One solution is to create a separate handler, i.e. /command.js
functions:
slack:
handler: app.handler
events:
- http:
path: slack/events
method: post
command:
handler: command.handler
events:
- http:
path: slack/command
method: post
[If your code is executing and u still have this error]
In my case using Slackbolt with js I forgot to add
await ack();
in called function so Slack api throw error.

How to add cache headers to Strapi API endpoint

I'd like to understand how to enable caching in Strapi for a specific (or any) API endpoint. At the moment when the browser hits my endpoint in the response headers I don't see any caching related headers. Is there a way to use etags and have a long cache time to allow the JSON response to be cached?
There is one mention of etags in the docs but I'm not sure how to implement. If anyone can provide more detailed information it would be appreciated.
At least for static files this can be done within Strapi itself. The middlewares documentation suggests, that there is already a middleware called public, which sets a Cache-Control header with its maxAge when it serves the files from the public/ directory.
But if you want to get your uploaded files cached (i.e. files within the public/uploads/ directory), that’s not enough, because the middleware strapi-provider-upload-local (not yet documented) runs first.
A recently published package solves this issue:
npm i strapi-middleware-upload-plugin-cache
Simply activate it by adding or modifying the config/middleware.js file with the following content:
module.exports = ({ env }) => ({
settings: {
'upload-plugin-cache': {
enabled: true,
maxAge: 86400000
}
}
});
I suggest you manage this kind of thing outside of Strapi.
With another service. For example, if you host you app on AWS, you can use CloudFront.

How to properly connect Nuxt.js with a laravel backend?

I am starting a new project, Nuxt.js for the frontend and Laravel for the backend.
How can I connect the two?
I have installed a new Nuxt project using create-nuxt-app, and a new laravel project.
As far as I have searched, I figured I need some kind of environment variables.
In my nuxt project, I have added the dotenv package and placed a new .env file in the root of the nuxt project.
And added CORS to my laravel project, as I have been getting an error.
The variables inside are indeed accessible from the project, and im using them
like this:
APP_NAME=TestProjectName
API_URL=http://127.0.0.1:8000
And accessing it like this:
process.env.APP_NAME etc'
To make HTTP calls, I am using the official Axios module of nuxt.js, and to test it i used it in one of the components that came by default.
The backend:
Route::get('/', function () {
return "Hello from Laravel API";
});
and from inside the component:
console.log(process.env.API_URL)//Gives 127.0.0.1:8000
//But this gives undefined
this.$axios.$get(process.env.API_URL).then((response) => {
console.log(response);
});
}
What am I doing wrong here?
I have tried to describe my setup and problem as best as I can. If I overlooked something, please tell me and I will update my question. Thanks.
Taking for granted that visiting https://127.0.0.1:8000/ in your browser you get the expected response, lets see what might be wrong in the front end:
First you should make sure that axios module is initialized correctly. Your nuxt.config.js file should include the following
//inclusion of module
modules: [
'#nuxtjs/axios',
<other modules>,
],
//configuration of module
axios: {
baseURL: process.env.API_URL,
},
Keep in mind that depending on the component's lifecycle, your axios request may be occurring in the client side (after server side rendering), where the address 127.0.0.1 might be invalid. I would suggest that you avoid using 127.0.0.1 or localhost when defining api_uris, and prefer using your local network ip for local testing.
After configuring the axios module as above, you can make requests in your components using just relative api uris:
this.$axios.$get('/').then(response => {
console.log(response)
}).catch(err => {
console.error(err)
})
While testing if this works it is very helpful to open your browser's dev tools > network tab and check the state of the request. If you still don't get the response, the odds are that you'll have more info either from the catch section, or the request status from the dev tools.
Keep us updated!
Nuxt has a routing file stucture to make it easy to set up server side rendering but also to help with maintainability too. This can cause Laravel and Nuxt to fight over the routing, you will need to configure this to get it working correctly.
I'd suggest you use Laravel-Nuxt as a lot of these small problems are solved for you.
https://github.com/cretueusebiu/laravel-nuxt

Cache internal routes with sw-precache

I'm creating a SPA using vanilla JavaScript and currently setting up sw-precache to handle the caching of resources. The service worker is generated as part of a gulp build and installed successfully. When I navigate to the root url (http://127.0.0.1:8080/) whilst offline the app shell displays, illustrating that resources are indeed cached.
I'm now attempting to get the SW to handle internal routing without failing. When navigating to http://127.0.0.1:8080/dashboard_index whilst offline I get the message 'Site can't be reached'.
The app handles this routing on the client side via a series of event listeners on the users actions or, in the case of using the back button, the url. When accessing one of these urls, no calls to the server should be made. As such, the service worker should allow these links to 'fall through' to the client side code.
I've tried a few things and expected this Q/A to solve the problem. I've included the current state of the generate-service-worker gulp task, and with this setup I'd expect to be able to access /dashboard_index offine. Once this is working I can adapt the solution to cover other routes.
Any help much appreciated.
gulp.task('generate-service-worker', function(callback) {
var rootDir = './public';
swPrecache.write(path.join(rootDir, 'sw.js'), {
staticFileGlobs: [rootDir + '/*/*.{js,html,png,jpg,gif,svg}',
rootDir + '/*.{js,html,png,jpg,gif,json}'],
stripPrefix: rootDir,
navigateFallback: '/',
navigateFallbackWhitelist: [/\/dashboard_index/],
runtimeCaching: [{
urlPattern: /^http:\/\/127\.0\.0\.1\:8080/getAllData, // Req returns all data the app needs
handler: 'networkFirst'
}],
verbose: true
}, callback);
});
update
The code to the application can be found here.
Removing the option navigateFallbackWhitelist does not chage the result.
Navigating to /dashboard_index whilst offline prints the following to the console.
GET http://127.0.0.1:8080/dashboard_index net::ERR_CONNECTION_REFUSED
sw.js:1 An unknown error occurred when fetching the script.
http://127.0.0.1:8080/sw.js Failed to load resource: net::ERR_CONNECTION_REFUSED
The same An unknown error occurred when fetching the script. is also duplicated in the 'application > service workers' tab of chrome debug tools.
It's also noted that the runtimeCaching option is not caching the json response returned from that route.
For the record, in case anyone else runs into this, I believe this answer from the comments should address the issue:
Can you switch from navigateFallback: '/' to navigateFallback:
'/index.html'? You don't have an entry for '/' in your list of
precached resources, but you do have an entry for '/index.html'.
There's some logic in place to automatically treat '/' and
'/index.html' as being equivalent, but that doesn't apply to what
navigateFallback is doing...

Laravel 5 CORS-issue vs. Ionic Angular

I am currently making an Ionic/Cordova-application with Laravel 5 as a Rest-server (my first time coding a PHP-server).
With Postman all my Get/Post/Update/Delete-functions work on Laravel, and on clientside (Ionic Cordova). I am able to send data to http://postcatcher.in using Chrome Allow-Control-Allow-Origin plugin.. Without the plugin, I get this error:
Since this problem apparently only happens in development-mode (when testing client-side in browser), I assume it's alright to develop with the plugin.
When I try to send data to Laravel through Ionic Cordova, I get this error (even with the Allow-Control-Allow-Origin plugin:
I have tried multiple things, such as https://github.com/barryvdh/laravel-cors, which just doesn't seem to work for me. Neither does suggestions in this forum, using CORS-middlewares. https://laracasts.com/discuss/channels/requests/laravel-5-cors-headers-with-filters
I assume that this is a Laravel-issue, but I am not 100% sure.
To publish the server, I use
php artisan serve, giving it localhost:8000.
For the application, I write: ionic serve, which gives it localhost:8100.
At last, this is the code I use to send data on Ionic-side:
.factory('userFactory', function($http, $q) {
return{
createuser : function(info) {
var deferred = $q.defer();
$http.post('localhost:8000/users', info)
.success(function(response, status){
deferred.resolve(response);
})
.error(function() {
console.log('SOMETHING WENT WRONG');
});
return deferred.promise;
}
}
})
Any help is really appreciated. Really stuck with this issue.
So it turns out that I'm an absolute idiot. I just needed to write "http://" in front on the URL. Rookie mistake.
EDIT: I'll keep the question open for just half an hour, in case anyone has advice for me.

Resources