If I set language as rootURL this works I am able to go to any route/subroute and current language will be present in url, but on page refresh browser is trying get app from that language folder any thoughts? :/ I am using Ember 1.11.
// router.coffee
`import Ember from 'ember';`
`import config from './config/environment';`
Router = Ember.Router.extend
location: config.locationType
rootURL: '/' + localStorage.getItem('locale') + '/'
// config/environment.js
module.exports = function(environment) {
var ENV = {
locationType: 'history',
baseURL: '/'
...
You shouldn't use rootURL for this purpose. Instead, create a route that will be a parent to all other routes:
//../app/router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend(
{
location: config.locationType
}
);
Router.map(
function ()
{
this.route(
'lang', { path: '/:lang' }, function ()
{
this.route('index', { path: '/' });
this.route('404', { path: '/*wildcard' });
this.route('your-route-name');
}
);
}
);
export default Router;
Than you can use afterModel method of lang route to determine desired locale:
//../app/routes/lang.js
import config from '../config/environment';
export default Ember.Route.extend(
{
afterModel: function (params)
{
var allowedLocales = config.i18n.allowedLocales;
var defaultLocale = config.i18n.defaultLocale;
this.set(
'i18n.locale',
params && params.lang && allowedLocales.indexOf(params.lang) > -1 ? params.lang : defaultLocale
);
}
}
);
And in index route you need to detect user's locale from browser's settings or use default one:
//../app/routes/index.js
import config from '../config/environment';
export default Ember.Route.extend(
{
beforeModel: function ()
{
var allowedLanguages = config.i18n.allowedLocales;
var language = config.i18n.defaultLocale;
if (navigator.languages) {
for (let lang of navigator.languages) {
if (allowedLanguages.indexOf(lang) > -1) {
language = lang;
break;
}
}
} else {
if (navigator.language) {
language = navigator.language;
} else {
if (navigator.userLanguage) {
language = navigator.userLanguage;
}
}
}
this.transitionTo('lang.index', { lang: language });
}
}
);
BTW, your Ember version is quite old. You may want to upgrade it to 1.13 (1.13.x shouldn't break your app, 2.x could).
Related
I have the middleware.js file within /myproject/pages/middleware.js:
export function middleware(request) {
console.log(1);
return NextResponse.redirect(new URL('/', request.url));
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ['/test'],
};
Now what I expect is when i go to the page /test then it should redirect me to /. However nothing happens and I see my standard 404 page.
Any ideas why?
NextJs version: 12.2.2
Latest versions of NextJS requires user to have a single middleware on the root folder.
Instead of {root}/pages/_middleware.js, try {root}/middleware.js
For next 13.0.2 / 13.0.1
if you are using appDir: true ( experimental )
if you want to hit middleware:
put middleware.ts in root project:
( as the same hierarchy as "app" folder, not inside app folder... )
make sure tsconfig has include: [..., "middleware.ts"]
make empty "pages" folder. ( based on issue )
will hit every request:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest ) {
console.log('lol!!!')
}
export const config = {
matcher: '/',
}
if your pages and middleware are not on the same level, then it won't work.
here is an example of middleware working with Cookies.
import { NextResponse } from "next/server";
export default function middleware(req){
let verify = req.cookies.get("loggedin");
let url = req.url
if(!verify && url.includes('/dashboard')){
return NextResponse.redirect("http://localhost:3000/");
}
if (verify && url === "http://localhost:3000/") {
return NextResponse.redirect("http://localhost:3000/dashboard");
}
}
My project is using Nuxt, and I would like to implement dynamic injection of my services. It means I just add a class to my specific folder, and the class will be automatically injected into the context.
For instance, these are my classes placed in nuxtApp/service:
// /service/foo.service.js
export class FooService {
constructor (context) {
this.context = context
}
functionFoo (param) {
console.log(`FooService.functionFoo: ${param}`)
}
}
// /service/bar.service.js
export class BarService {
constructor (context) {
this.context = context
}
functionBar (param) {
console.log(`BarService.functionBar: ${param}`)
}
}
And this is how my plugin currently looks like, but I would like to automate it:
// /plugins/service-loader.js
import { FooService } from '../service/foo.service'
import { BarService } from '../service/bar.service'
export default ({ app }, inject) => {
const fooService = new FooService(app)
inject('fooService', fooService)
const barService = new BarService(app)
inject('barService', barService)
}
Is it possible to create automatically loading of services placed in the /service folder, and then inject their instance into the context?
You could use a Nuxt module to provide plugins for ~/service/*.service.js. The module would scan the service/ directory, and call addPlugin() for each .service.js file:
// ~/modules/service-loader.js
import path from 'path'
import glob from 'glob'
export default function serviceLoader() {
glob(path.resolve(__dirname, '../service/**/*.service.js'), { follow: true }, (err, files) => {
if (err) throw err
for (const file of files) {
const exportedMembers = Object.keys(require(file))
if (!exportedMembers.length) return
const className = exportedMembers[0]
this.addPlugin({
src: path.resolve(__dirname, './service-template.js'),
fileName: path.basename(file),
options: {
className,
propName: className.slice(0,1).toLowerCase() + className.substring(1),
moduleName: file,
}
})
}
})
}
// ~/modules/service-template.js
import { <%= options.className %> } from '<%= options.moduleName %>'
export default ({ app }, inject) => {
const <%= options.propName %> = new <%= options.className %> (app)
inject('<%= options.propName %>', <%= options.propName %>)
}
Install this module under the modules array in your Nuxt config:
// nuxt.config.js
export default {
modules: [
'~/modules/service-loader'
],
}
I am trying to pass data that I get from my module options down to a plugin. So let's say this is my module:
module.exports = function (moduleOptions) {
const options = {
...this.options.moduleName,
...moduleOptions
}
this.addPlugin({
src: resolve(__dirname, 'plugin.js'),
options
})
}
and this is my plugin
import { createStore } from 'lib';
export default async ({ store, app }) => {
const settings = {
axios: app.$axios,
models: <% options.models %>
}
settings.axios = app.$axios;
createStore(settings).install()(store)
};
and this is my config
const { resolve } = require('path')
module.exports = {
rootDir: resolve(__dirname, '..'),
buildDir: resolve(__dirname, '.nuxt'),
srcDir: __dirname,
render: {
resourceHints: false
},
modules: [
'moduleName'
],
moduleName: {
{ models: require(resolve(__dirname, '../example/models')) }
}
}
it throws
axios: app.$axios,
7 | models:
> 8 | }
where models is just empty, nothing behind it. No null, no undefined.
But if I do <% console.log(options.models) %> it will show the models that I've loaded. Btw models is just an array of classes.
These models must be configurable, so how do I pass these data from my nuxt.config.js via a module to my plugin?
Hope somebody knows :)
I've worked around this issue using an require in my plugin instead of my config.
after converting a simple react module to es6 class; i got some gulp parsing errors.
var React = require('react');
// import React from 'react';
class UdpComp extends React.Component {
constructor (props){
super(props);
this.state = { udpinput: props.udpinput };
},
render: function() {
return(
<div className="udpText">
<h2>UDP-INPUT: {this.state.udpinput}</h2>
</div>
) // return
} // render
})// UdpComp
export default UdpComp;
ok, my gulpfile.babel.js looks like this:
var gulp = require('gulp'),
browserify = require('gulp-browserify'),
concatCss = require('gulp-concat-css'),
sass = require('gulp-sass'),
run = require('gulp-run');
var src = './process',
app = './app';
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded'
}; // https://www.sitepoint.com/simple-gulpy-workflow-sass/
gulp.task('js', function() {
return gulp.src( src + '/js/apprender.js' )
.pipe(browserify({
transform: 'reactify',
extensions: 'browserify-css',
debug: true
}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(gulp.dest(app + '/js'));
});
gulp.task('html', function() {
gulp.src( src + '/**/*.html');
});
gulp.task('css', function() {
gulp.src( src + '/css/*.css')
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(concatCss('app.css'))
.pipe(gulp.dest(app + '/css'));
});
gulp.task('fonts', function() {
gulp.src('node_modules/bootstrap/dist/fonts/**/*')
.pipe(gulp.dest(app + '/fonts'));
});
gulp.task('watch', ['serve'], function() {
gulp.watch( src + '/js/**/*', ['js']);
gulp.watch( src + '/css/**/*.css', ['css']);
gulp.watch([ app + '/**/*.html'], ['html']);
});
gulp.task('serve', ['html', 'js', 'css'], function() {
run('electron app/main.js').exec();
});
gulp.task('default', ['watch', 'fonts', 'serve']);
when calling gulp I get
\process\js\UdpCompReact.js: Parse Error: Line 14: Unexpected
identifier error
why, how can I parse es6 code?
Can't see what's on line 14 but I'd guess it's the comma right after your constructor. As opposed to ES5 "classes", ES6 classes don't require (and don't allow) commas between methods. Just remove it and it should work (or at least get past line 14)
You need a transpiler that converts it to ES5, afterwards pipe it in the gulp task. I use babel and there is a gulp-babel npm package
I changed my code to this, when using the older version the transpiling works.
import React from 'react' throws an error.
// var React = require('react');
import React from 'react';
class UdpComp extends React.Component {
constructor (props){
super(props);
this.state = { udpinput: this.props.udpinput };
}
render () {
return(
<div className="udpText">
<h2>UDP-INPUT: {this.state.udpinput}</h2>
</div>
) // return
} // render
}; // UdpComp
module.exports = UdpComp;
// export default UdpComp;
sorry for that (maybe) silly question. Im super new to this topic!
I created a custom authorizer:
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
export default Base.extend({
authorize: function(jqXHR, requestOptions) {
var accessToken = this.get('session.content.secure.token');
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
jqXHR.setRequestHeader('Authorization', 'Bearer ' + accessToken);
}
}
});
And now i want to include the token in a ajax request in my controller (this is my code without the token send):
// app/controllers/workouts.js
import Ember from 'ember';
import config from '../config/environment';
export default Ember.Controller.extend({
requestEndpoint: config.ServerIp+'/workouts',
workouts: function() {
Ember.$.ajax({
type: "GET",
url: requestEndpoint
}).success(function(data) {
return data;
})
}.property()
});
Thank you very much for helping and understanding this great module!
You could have something like this.
In your authorizer:
// app/authorizers/your-authorizer.js
import BaseAuthorizer from 'ember-simple-auth/authorizers/base';
export default BaseAuthorizer.extend({
authorize(data, block) {
const accessToken = data.accessToken; //Data is the response returned by the server
if (!Ember.isEmpty(accessToken)) {
block('Authorization', `Bearer ${accessToken}`);
}
}
});
The adapter will take care of adding the authorization header to all your requests:
// app/adapters/application.js
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
authorizer: 'authorizer:your-authorizer'
});
If you are not using ember data, you can take a look the way this mixin works to create your own adapter: data-adapter-mixin
To protect your route from access if the users are not logged, you need to add the authenticated mixin:
// app/routes/home.js
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Route.extend(AuthenticatedRouteMixin, {
...
});
And don't forget to set some configuration
// config/environment.js
...
var ENV = {
...
'ember-simple-auth': {
authenticationRoute: 'login',
routeAfterAuthentication: 'home',
routeIfAlreadyAuthenticated: 'home'
}
}