Hello I need to know how can I solve this issue.
What I want to know is how can I open a page with parameters from data.
Here is flow What I want to make.
several person receives email. there is a button to link to a page with their id.
When they push the button, server identifies them and send their name from database.
redirect them to main page. with their name data.
main page(vue) shows their name like “welcome home. Mr Smith”
I’m stuck between step 3 and 4. I’m sending their name data as query.
But don’t know how to receive them.
I thought it can be used as props. but it only shows ‘undefined’
here is my node js code.
res.redirect(url.format({
pathname:"/",
query: {
"name": rows[0].name,
"familyname": rows[0].familyname,
"gender":rows[0].gender
}
}));
and this is vue router part. (router.js)
routes: [
{
path: '',
props: true,
component: () => import('./layouts/main/Main.vue'),
children: [ ... ]
}]
and I’m making my main.vue code like this.
export default {
props: ['name','familyname','gender'],
methods: {
showprops() {
alert(this.$props.name);
}
},
created() {
this.showprops();
}
Current result is undefined when alert(this.$props.name) is called.
How can I solve this issue?
Thank you in advance.
$route.query
Looks like you are including your parameters as query parameter, e.g. /?name=xxx&familyname=xxx&gender=xxx . To get queryparameters from vue route you have to use this.$route.query .
$route.props
To have props like this.$route.props , this would require a url like /user/12345/bob and a vue router setup like
routes: [
{ path: '/user/:id/:name', component: User, props: true }
]
Converting query parameters to vue router props
In the official vue router docs you'll find a very nice example on how to use Function Mode to convert query parameters to props ( https://router.vuejs.org/guide/essentials/passing-props.html#function-mode ) .
const router = new VueRouter({
routes: [
{ path: '/search',
component: SearchUser,
props: (route) => ({ query: route.query.q })
}
]
})
From the example above the URL /search?q=vue would pass {query: 'vue'} as props to the SearchUser component.
Related
I am creating a GraphQL app using Next.js for server side rendering. As you might know, there is a recommended way to implement clean URL using Express. I am trying to achieve the same using graphql-yoga but it's not working.
I have tried server.express.get('/route', ...) and server.get('/route', ...) but nothing is working. In the documentation they have given server.express.get(server.options.endpoint, handler()) but it's not working for me.
Has anyone ever implemented clean Next.js URL in a GraphQL Yoga server, and how did you achieve it? Below is how I am creating the server.
function createServer() {
return new GraphQLServer({
typeDefs: "src/schema.graphql",
resolvers: {
Mutation,
Query
},
context: req => ({ ...req, db })
});
}
const server = createServer();
server.express.post('/product/name', (req,res,next) => {
//this is where i want to implement next clean url
//but it's not working
console.log('Am never reached..');
next();
})
With the new versions of Next.js, creating clean URL is straightforward.
Create a parameterised page (e.g. pages/post/[pid].js):
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
More info in the Next.js documentation regarding dynamic routes.
You can then link to it and show the desired URL:
<Link href="/post/[pid]" as="/post/abc">
<a>First Post</a>
</Link>
I'm trying to have a children route-view inside my main page, and can't find a way to accomplish this in vuepress.
This is how I would normally accomplish this in Vue, in router.js
routes: [
{
path: '/',
name: 'home',
component: Home,
children: [
{
path: '/work/:worktitle',
name: 'workpage',
// component: () => import(/* webpackChunkName: "about" */ './views/WorkView.vue'),
component: WorkView,
props: true
}
]
}
]
But I don't know where can I put such code in vuepress. (no router.js)
I am trying to accomplish this because I'm trying to have a collection of links in my homepage, and when clicked, I'd like to have the pages of those links rendered as a modal without going to a new page. But I'd like to retain the ability to link directly to these modals.
use .vuepress/enhanceApp.js with router.addRoutes
// async function is also supported, too
export default ({
Vue, // the version of Vue being used in the VuePress app
options, // the options for the root Vue instance
router, // the router instance for the app
siteData, // site metadata
isServer // is this enhancement applied in server-rendering or client
}) => {
// ...apply enhancements to the app
router.addRoutes([
// ...
])
}
I'm building a web app using Angular 7 for the frontend and NodeJS, MongoDB and ExpressJS for the backend. The application runs as intended as long as I interact with the application to navigate, but when I manually type the path, it seems like it doesn't hit the component for the route. It works all good locally, but not on Heroku.
Here's is my app-routing.module.ts:
const routes: Routes = [{
path: "login",
component : LoginComponent
},
{
path: "registration",
component : SignupComponent
},
{
path: "votes",
component : VotesComponent
},
{
path: "votes/:website",
component : VoteComponent
},
{
path: "**",
redirectTo: "votes"
}
];
#NgModule({
imports: [CommonModule, RouterModule.forRoot(routes, { enableTracing: false})],
exports: [RouterModule]
})
export class AppRoutingModule { }
All my routes in Express is prefixed with /api/, such as:
app.get('/api/votes', (req, res, next) => {
const limit = parseInt(req.query.limit)
db.getVotes(limit).then((votes) => {
res.json(votes);
});
});
I check the jwt like this:
app.use(
checkJwt({ secret: process.env.JWT_SECRET }).unless({ path: [
{ url: "/api/authenticate", methods: ['POST'] },
{ url: "/api/votes", methods: ["GET"]}]})
);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).send({ error: 'Not authorized.' });
};
});
My call to votes is performed like this:
private baseUrl = environment.apiUrl;
this.http.get<any[]>(`${this.baseUrl}/votes`, this.httpOptions))).subscribe(data => {
this.data = data;
});
The baseUrl is defined as follows in the evironment.prod.ts:
export const environment = {
production: true,
apiUrl: '/api'
};
Here comes the problem. If I go to my deployment on Heroku and access https://myurl.com I'm redirected to https://myurl.com/votes and I can see the requested url is https://myurl.com/api/votes, so thats all fine and I get my angular application with all the data. But if I manually type in https://myurl.com/votes I get JSON back in the browser with error "Not authorized", and I can see that the requested URL is https://myurl.com/votes, instead of https://myurl.com/api/votes. Any ideas whats causing this? It seems like Angular is not routing it properly. When it's typed manually it doesn't hit any of my components.
For non-match route path, the router configuration should include below one.
{
path: "",
component: "404NotFoundComponent"
}
Im am trying to redirect a user after (in the API) it is detected the user is no longer logged in.
For instance, the user starts an action (PUT) to the api, the api checks the user status, if logged in, the action is performed and data is returned. If not, the user needs to be redirected to the login-page, the loginroute (/login) is defined in the Angular5 router.
This works nice, if logged in, all is fine.
If not logged in, it is detected and Logged, but the redirect doesnt work, at first it tried to use PUT on /login resulting in 404, that doenst work so i added 303, now it GETs on /login. But... in my browser console i get...
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad ( etc
Somehow it seems it is trying to parse the page as JSON???
What is going on here? I hope someone can give me a hint so i can forward to this page if someone is not logged in :)
Some code (Using Angular 5)...
In node/express/passport there is a small bit of middleware to check status...
function isTeacher(req, res, next) {
if (req.isAuthenticated() && (req.user.google.role=="teacher" || req.user.google.role=="admin") )
return next();
console.log("Not loggedin");
res.redirect(303, '/login');
};
In the router...
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full'},
{ path: 'login', component: LoginComponent},
{ path: 'studentlists', component: ListselectorComponent},
{ path: 'studentlisteditor/:listid', component: StudentlisteditorComponent},
{ path: 'teacherlists', component: TeacherlistselectorComponent},
{ path: 'teacherlisteditor/:listid',
component: TeacherlisteditorComponent,
children: [
{path: 'results', component: TeacherresultsComponent },
{path: 'edit', component: ListeditorComponent },
]
},
];
(I am a real beginner so there probably are more weird things in my code... sorry for that, all input welcome ;)
My suggestion for you is to avoid the redirection in the backend and do it from the frontend, what I'll do: In your isTeacher method if the user is not allowed return a response indicating it's not valid and then in your Angular app use a route guard to check this answer and if it's not the expected then redirect to login. Angular official docs about route guards
I'm running express.js with jade. Now I realize that I need to send a user object to jade every time:
var renderObject = {
navigation: [{
url: "/",
title: "Home"
}],
user: user
}
res.render('MyTemplate', renderObject);
However, I'm rather deep into the project and have a lot of routes where res.render is called. So now, lazy as I am, I started to look if there's a way to jack in to the renderer before the renderer is actually called.
Pseudocode:
app.beforeRendering(function(template,renderObject,next) {
renderObject.user = GLOBAL.myUserObject;
})
You can set properties on res.locals to be included in all renders:
res.locals.nav = [{
url: "/",
title: "Home"
}];
res.locals.user = user;
Or perhaps replace the whole object in one step:
res.locals = {
navigation: [{
url: "/",
title: "Home"
}],
user: user
};