angular 6 universal issue 'Module not found: Error: Can't resolve './dist/server/main' in '/var/www/html/angular6/testing'' - angular6

I am trying to do universal rendering in angular 6 with the help of this link.I followed the steps mentioned in the above link,but it shows following error.
ERROR in ./server.ts
Module not found: Error: Can't resolve './dist/server/main' in '/var/www/html/angular6/testing'
# ./server.ts 16:9-38
server.ts
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '#angular/core';
import * as express from 'express';
import { join } from 'path';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 3005;
const DIST_FOLDER = join(process.cwd(), 'dist');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
// Express Engine
import { ngExpressEngine } from '#nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '#nguniversal/module-map-ngfactory-loader';
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
can anyone please help me to solve this issue?I already spend lot of time in this issue.

There were a number of breaking changes and the documentation isn't up to date.
Step 3 of https://github.com/angular/angular-cli/wiki/stories-universal-rendering fixed the issue you mentioned for me.
I had been using the nx workspace generator and it was serving up the server into the browser rather than building the files in angular.json as outlined below:
"architect": {
"build": { ... }
"server": {
"builder": "#angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/your-project-name-server",
"main": "src/main.server.ts",
"tsConfig": "src/tsconfig.server.json"
}
}
}

Related

Firebase Cloud Function with Swagger: Error: could not handle the request

I have this code in a function called docs:
const functions = require("firebase-functions");
const express = require("express");
const swaggerUi = require("swagger-ui-express");
const swaggerJsdoc = require("swagger-jsdoc");
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "API",
version: "1.0.0",
},
},
apis: ["../**/*.function.js"],
};
const openapiSpecification = swaggerJsdoc(options);
console.log("🚀 ", openapiSpecification);
const app = express();
app.use(
"/",
swaggerUi.serve,
swaggerUi.setup(openapiSpecification, {
swaggerOptions: {
supportedSubmitMethods: [], //to disable the "Try it out" button
},
})
);
module.exports = functions.https.onRequest(app);
But every time I hit the URL, this error gets returned:
Error: could not handle the request
URL:
https://REGION-PROJECT.cloudfunctions.net/docs
The deps above are all installed.
Any idea what is causing this issue?
Or better yet, how can I serve an endpoint for Swagger docs?
Please keep in mind that all other functions don't use express; most are callable. Just this one function uses it, so not sure if the mixing not supported.
Here's the folder structure:
package.json
index.js
app
auth
login.function.js
users
createUser.function.js
Inside index.js, the functions get loaded and added to the exports dynamically. This setup works fine and deploys well, so no issues there.

Next.js Redirect from / to another page

I'm new in Next.js and I'm wondering how to redirect from start page ( / ) to /hello-nextjs for example. Once user loads a page and after that determine if path === / redirect to /hello-nextjs
In react-router we do something like:
<Switch>
<Route path="/hello-nextjs" exact component={HelloNextjs} />
<Redirect to="/hello-nextjs" /> // or <Route path="/" exact render={() => <Redirect to="/hello-nextjs" />} />
</Switch>
Update: Next.js >= 13 with AppDir enabled
You can use next/navigation to redirect both in client components and server components.
Ex. in pages :
import { redirect } from 'next/navigation';
export default async function Home({ params }) {
redirect('/hello-nextjs');
// ...
}
Ex. In client components:
'use client';
import { useEffect } from 'react';
import { redirect } from 'next/navigation';
export const Home= () => {
useEffect(() => {
redirect('/hello-nextjs');
}, []);
return <p></p>;
};
Update: Next.js >= 12.1
As #warfield pointed out in his answer from next.js >= 12.1 relative URLs are no longer allowed in redirects and using them will throw an error. I'm reposting here his answer for more visibility :
To redirect using middleware with Next.js >= 12.1:
Create a middleware.ts (or .js) file at the same level as your pages directory
Export a middleware function
Create an absolute URL and pass it to redirect
TypeScript example middleware.ts:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone()
if (url.pathname === '/') {
url.pathname = '/hello-nextjs'
return NextResponse.redirect(url)
}
}
Update: Next.js >= 12
Now you can do redirects using middleware, create a _middleware.js file inside the pages folder (or any sub folder inside pages)
import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req, ev) {
const { pathname } = req.nextUrl
if (pathname == '/') {
return NextResponse.redirect('/hello-nextjs')
}
return NextResponse.next()
}
Update: Next.js >= 10
From Next.js 10 you can do server side redirects (see below for client side redirects) with a redirect key inside getServerSideProps or getStaticProps :
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
// or use context.resolvedUrl for conditional redirect
// if(context.resolvedUrl == "/")
if (!data) {
return {
redirect: {
destination: '/hello-nextjs',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}
Note : Using getServerSideProps will force the app to SSR,also redirecting at build-time is not supported , If the redirects are known at build-time you can add those inside next.config.js
In next.js you can redirect after the page is loaded using Router ex :
import Router from 'next/router'
componentDidMount(){
const {pathname} = Router
if(pathname == '/' ){
Router.push('/hello-nextjs')
}
}
Or with Hooks :
import React, { useEffect } from "react";
import Router from 'next/router'
...
useEffect(() => {
const {pathname} = Router
if(pathname == '/' ){
Router.push('/hello-nextjs')
}
});
If you want to prevent the flashing before the redirect you can use a simple trick :
import React, { useEffect,useState } from "react";
import Router from 'next/router'
const myPage = ()=>{
const [loaded,setLoaded] = useState(false)
useEffect(() => {
const {pathname} = Router
// conditional redirect
if(pathname == '/' ){
// with router.push the page may be added to history
// the browser on history back will go back to this page and then forward again to the redirected page
// you can prevent this behaviour using location.replace
Router.push('/hello-nextjs')
//location.replace("/hello-nextjs")
}else{
setLoaded(true)
}
},[]);
if(!loaded){
return <div></div> //show nothing or a loader
}
return (
<p>
You will see this page only if pathname !== "/" , <br/>
</p>
)
}
export default myPage
I would say that in general is not a good/elegant approach to do client redirects when you can use next.config.js redirects or even better use conditional render of components.
I have create a simple repo with all the examples above here.
Caveat
First, you should asses whether you need client-side redirection (within React), server-side redirection (301 HTTP response) or server-side redirection + authentication (301 HTTP response but also having some logic to check authentication).
This is the most complete answer I could write. But, in most scenarios, you do not need any of this. Just redirect as you would do in any React app. Prefer client-side redirections first. Just using useEffect + router.push, and that's it.
Server-side redirection are tempting, in particular when you want to "secure" private pages, but you should assess whether you really need them. Usually, you don't. They induce unexpected complexity, like managing auth token and refresh token. Instead, you may want to add a gateway server, a reverse proxy or whatever upfront server to your architecture for instance to handle those kind of checks.
Keep in mind that Next.js are just React app, and using Next.js advanced features like SSR comes at a cost that should be justified in your context.
Next 9.5 update
As stated by #Arthur in the comments, 9.5 also include the possibilities to setup redirects in next.config.js.
The limitations of this feature are not yet clear to me, but they seem to be global redirections, e.g. when you need to move a page or to allow access only during a limited period.
So they are not meant to handle authentication for instance, because they don't seem to have access to the request context. Again, to be confirmed.
Next 10 new doc update
This solution is specific to redirection depending on authentication.
Authentication patterns are now documented
I am not fond of authenticated from getServerSideProps, because it's in my opinion quite too late and can be difficult to set up with advanced patterns such as handling refresh token. But that's the official solution.
You may also want to check the approach documented in this ticket based on how Vercel's dashboard works (at the time of writing), that prevents flash of unauthenticated content
Next 10.2 header and cookies based rewrites update
Next 10.2 introduces Rewrites based on headers and cookies.
That's a great way to redirect server-side, based on the presence of an authentication cookie or header.
However, keep in mind that this is not a secure redirection. User can alter their request headers with a false token. You still need a gateway, a reverse proxy or an upfront server to actually check token validity and correctly set the headers.
Edit: note that the URL won't change. A rewrite points an URL to an existing page of your application, without changing the URL => it allows you to have "virtual" URLs.
Example use case: imagine you have a page src/contact.tsx, that is translated, and i18n redirection setup. You can translate the page name itself ("contact") by rewriting /de/kontact to /de/contact.
Next 12 update
Now middlewares gives you full-control on server-side redirects.
However, keep in mind again, that most of the time a client-side redirect and check is just enough.
Outdated Next 9.4 answer (links are dead sorry)
Hi, here is an example component working in all scenarios:
Vulcan next starter withPrivate access
Example usage here
The answer is massive, so sorry if I somehow break SO rules, but I don't want to paste a 180 lines piece of code. There is no easy pattern to handle redirection in Next, if you want to both support SSR and static export.
The following scenarios each need a specific pattern:
server side rendering: we render the page if allowed, HTTP redirect if not
static rendering (server-side): we render nothing, but we still include the page into the build
client side rendering, after a static export: we check client side if the user is auth, and redirect or not. We display nothing (or a loader) during this check or if we are redirecting.
client side rendering after a client redirect using next/router: same behaviour.
client side rendering after SSR: we use props passed by getInitialProps to tell if the user is allowed, directly at first render. It's just a bit faster, you avoid a blank flash.
At the time of writing (Next 9.4), you have to use getInitialProps, not getServerSideProps, otherwise you lose the ability to do next export.
Even more outdated old answer (works, but will have a messy static render)
Semi-official example
The with-cookie-auth examples redirect in getInitialProps. I am not sure whether it's a valid pattern or not yet, but here's the code:
Profile.getInitialProps = async ctx => {
const { token } = nextCookie(ctx)
const apiUrl = getHost(ctx.req) + '/api/profile'
const redirectOnError = () =>
typeof window !== 'undefined'
? Router.push('/login')
: ctx.res.writeHead(302, { Location: '/login' }).end()
try {
const response = await fetch(apiUrl, {
credentials: 'include',
headers: {
Authorization: JSON.stringify({ token }),
},
})
if (response.ok) {
const js = await response.json()
console.log('js', js)
return js
} else {
// https://github.com/developit/unfetch#caveats
return await redirectOnError()
}
} catch (error) {
// Implementation or Network error
return redirectOnError()
}
}
It handles both server side and client side. The fetch call is the one that actually get the auth token, you might want to encapsulate this into a separate function.
What I would advise instead
 1. Redirect on server-side render (avoid flash during SSR)
This is the most common case. You want to redirect at this point to avoid the initial page flashing on first load.
MyApp.getInitialProps = async appContext => {
const currentUser = await getCurrentUser(); // define this beforehand
const appProps = await App.getInitialProps(appContext);
// check that we are in SSR mode (NOT static and NOT client-side)
if (typeof window === "undefined" && appContext.ctx.res.writeHead) {
if (!currentUser && !isPublicRoute(appContext.router.pathname)) {
appContext.ctx.res.writeHead(302, { Location: "/account/login" });
appContext.ctx.res.end();
}
}
return { ...appProps, currentUser };
};
 2. Redirect in componentDidMount (useful when SSR is disabled, eg in static mode)
This is a fallback for client side rendering.
componentDidMount() {
const { currentUser, router } = this.props;
if (!currentUser && !isPublicRoute(router.pathname)) {
Router.push("/account/login");
}
}
I could not avoid flashing the initial page in static mode add this point, because you can't redirect during the static build, but it seems better than the usual approaches. I'll try to edit as I make progress.
Full example is here
Relevant issue, which sadly ends up with a client only answer
New issue I've opened regarding redirecton
There are three approaches.
1.Redirect on events or functions:
import Router from 'next/router';
<button type="button" onClick={() => Router.push('/myroute')} />
2.Redirect with hooks:
import Router , {useRouter} from 'next/router';
const router = useRouter()
<button type="button" onClick={() => router.push('/myroute')} />
3.Redirect with Link:
based on Nextjs docs the <a> tag is neccessary inside the link for things like open in a new tab!
import Link from 'next/link';
<Link href="/myroute">
<a>myroute</a>
</Link>
There are some other options for serverside routing which is asPath. in all described approaches you can add asPath to redirect both client and server side.
Edit 13.12.2022
1.Redirect with Link doesn't require anchor tag anymore!
import Link from 'next/link';
<Link href="/myroute">
my route
</Link>
2.Use Nextj.js Redirects
in next.config.js
module.exports = {
async redirects() {
return [
{
source: '/someroute',
destination: '/myroute',
permanent: true,
},
]
},
}
Next.js 10+ is offering us some extra and elegant solution to make a redirection.
SERVER-SIDE - you should use getServerSideProps
The example below assume that we have some extra session to check (but can be
anything that you want). If the session is empty and we are on the server-side
(context.res), that's mean that the user is not logged in and we should
redirect to the login page (/login).. In another way we can pass session
to props and redirect to the /dashboard:
import { getSession } from 'next-auth/client';
export const getServerSideProps = async (context) => {
const session = await getSession(context);
if(context.res && !session) {
return {
redirect: {
permanent: false,
destination: '/login'
}
}
}
return {
props: { session },
redirect: {
permanent: false,
destination: '/dashboard'
}
}
}
CLIENT-SIDE - you can use for example useRouter hook:
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/client';
const router = useRouter();
const [ session, loading ] = useSession();
if (typeof window !== 'undefined' && loading) return null;
if (typeof window !== 'undefined' && !session) {
router.push('/login');
}
router.push('/dashboard');
More info here: https://github.com/vercel/next.js/discussions/14890
Valid for NextJS 9.5.0+
Create next.config.js file
add source and destination url (you can set to permanent redirect if external domain)
module.exports = {
async redirects() {
return [
{
source: '/team',
destination: '/about',
permanent: false,
},
{
source: "/blog",
destination:
"https://blog.dundermifflin.com",
permanent: true,
},
];
},
};
https://github.com/vercel/next.js/tree/canary/examples/redirects
Here are 2 copy-paste-level examples: one for the Browser and one for the Server.
https://dev.to/justincy/client-side-and-server-side-redirection-in-next-js-3ile
Let's say you want to redirect from your root (/) to a page called home: (/home)
In your main index file, paste this:
Client Side
import { useRouter } from 'next/router'
function RedirectPage() {
const router = useRouter()
// Make sure we're in the browser
if (typeof window !== 'undefined') {
router.push('/home')
}
}
export default RedirectPage
Server Side
import { useRouter } from 'next/router'
function RedirectPage({ ctx }) {
const router = useRouter()
// Make sure we're in the browser
if (typeof window !== 'undefined') {
router.push('/home');
return;
}
}
RedirectPage.getInitialProps = ctx => {
// We check for ctx.res to make sure we're on the server.
if (ctx.res) {
ctx.res.writeHead(302, { Location: '/home' });
ctx.res.end();
}
return { };
}
export default RedirectPage
#Nico's answer solves the issue when you are using classes.
If you are using function you cannot use componentDidMount. Instead you can use React Hooks useEffect .
import React, {useEffect} from 'react';
export default function App() {
const classes = useStyles();
useEffect(() => {
const {pathname} = Router
if(pathname == '/' ){
Router.push('/templates/mainpage1')
}
}
, []);
return (
null
)
}
In 2019 React introduced hooks. which are much faster and efficient than classes.
In NextJs v9.5 and above you can configure redirects and rewrites in the next.config.js file.
But if you are using trailingSlash: true ensure that the source path ends with a slash for proper matching.
module.exports = {
trailingSlash: true,
async redirects() {
return [
{
source: '/old/:slug/', // Notice the slash at the end
destination: '/new/:slug',
permanent: false,
},
]
},
}
You also need to account for other plugins and configurations that may affect routing, for example next-images.
Documentation: https://nextjs.org/docs/api-reference/next.config.js/redirects
redirect-to.ts
import Router from "next/router";
export default function redirectTo(
destination: any,
{ res, status }: any = {}
): void {
if (res) {
res.writeHead(status || 302, { Location: destination });
res.end();
} else if (destination[0] === "/" && destination[1] !== "/") {
Router.push(destination);
} else {
window.location = destination;
}
}
_app.tsx
import App, {AppContext} from 'next/app'
import Router from "next/router"
import React from 'react'
import redirectTo from "../utils/redirect-to"
export default class MyApp extends App {
public static async getInitialProps({Component, ctx}: AppContext): Promise<{pageProps: {}}> {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
if (ctx.pathname === "" || ctx.pathname === "/_error") {
redirectTo("/hello-next-js", { res: ctx.res, status: 301 }); <== Redirect-To
return {pageProps};
}
return {pageProps};
}
render() {
const {Component, pageProps} = this.props;
return <Component {...pageProps}/>
}
}
I have implemented this functionality in my Next.JS app by defining a root page this does the redirect server side and client side. Here is the code for the root page:
import { useEffect } from "react";
import Router from "next/router";
const redirectTo = "/hello-nextjs";
const RootPage = () => {
useEffect(() => Router.push(redirectTo));
return null;
};
RootPage.getInitialProps = (ctx) => {
if (ctx.req) {
ctx.res.writeHead(302, { Location: redirectTo });
ctx.res.end();
}
};
export default RootPage;
Next.js >= 12.1
Relative URLs are no longer allowed in redirects and will throw:
Error: URLs is malformed. Please use only absolute URLs.
To redirect using middleware with Next.js >= 12.1:
Create a middleware.ts (or .js) file at the same level as your pages directory
Export a middleware function
Create an absolute URL and pass it to redirect
TypeScript example middleware.ts:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone()
if (url.pathname === '/') {
url.pathname = '/hello-nextjs'
return NextResponse.redirect(url)
}
}
🤷‍♂ī¸ useEffect will redirect but jump immediately back to current page
✅ useLayoutEffect works like a charm:
const router = useRouter();
useLayoutEffect(() => {
router.isFallback && router.replace("/course");
}, [router]);
ℹī¸ I've used the same code above for useEffect.
If your intention is to ensure your app is running like a SPA and wanting to intercept an incoming invalid (or valid) pathname, which the user pasted into the address bar, then here's a fast/hacky way to do that.
Assume your paths are,
enum ERoutes {
HOME = '/',
ABOUT = '/about',
CONTACT = '/contact'
}
Add a custom _error page if you don't have one already, and add this to it:
import React from 'react';
import { NextPage } from 'next';
import { useDispatch } from 'react-redux';
import { useRouter } from 'next/router';
const Error: NextPage = () => {
const { asPath, push } = useRouter();
const dispatch = useDispatch();
React.useEffect(() => {
const routeValid = Object.values(ERoutes).includes(asPath);
if (routeValid) {
// do some stuff, such as assigning redux state to then render SPA content in your index page
} else {
// you can either continue to render this _error component, or redirect to your index page,
// where you may have your own error component that is displayed based on your app state.
// In my case, I always redirect to '/' (as you can see below, where I push('/'), but before doing so,
// I dispatch relevant redux actions based on the situation
}
// I redirect to root always, but you can redirect only if routeValid === true
push('/');
}, []);
return (
<div>Error because '{asPath}' does not exist</div>
);
};
export default Error;
Redirects
Starting from Next.js 9.5 you are now able to create a list of redirects in next.config.js under the redirects key:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
];
},
};
Ofiicial Docs
Here's the middleware solution to avoid URLs is malformed. Please use only absolute URLs error.
Also, using paths object may be the cleaner way to handle redirection.
// pages/_middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export async function middleware(req: NextRequest) {
const { pathname, origin } = req.nextUrl;
const paths: { [key: string]: string } = {
'/admin/appearance': `${origin}/admin/appearance/theme`,
};
const rePath = paths[pathname];
if (rePath) return NextResponse.redirect(rePath);
else return NextResponse.next();
}
You can set a base path. Next Js allows you to do this. For example, to use /login instead of / (the default), open next.config.js and add the basePath config:
const nextConfig = {
basePath: "/login",
};
module.exports = nextConfig;
You can also check out their docs here https://nextjs.org/docs/api-reference/next.config.js/basepath

How can I have multiple API endpoints for one Google Cloud Function?

I have a Google Cloud Function which contains multiple modules to be invoked on different paths.
I am using the serverless framework to deploy my functions, but it has the limitation of only one path per function.
I want to use multiple paths in one function just like we can in the AWS serverless framework.
Suppose a user cloud function will have two paths /user/add as well as /user/remove; both the paths should invoke the same function.
Something like this:
serverless.yml
functions:
user:
handler: handle
events:
- http: user/add
- http: user/remove
How can I have multiple API endpoints for one GCF?
Yes, indeed there is no actual REST service backing up Google Cloud Functions. It uses out of the box HTTP triggers.
To hustle the way around, I'm using my request payload to determine which action to perform. In the body, I'm adding a key named "path".
For example, consider the Function USER.
To add a user:
{
"path":"add",
"body":{
"first":"Jhon",
"last":"Doe"
}
}
To remove a user:
{
"path":"remove",
"body":{
"first":"Jhon",
"last":"Doe"
}
}
If your operations are purely CRUD, you can use request.method which offers verbs like GET, POST, PUT, DELETE to determine operations.
You could use Firebase Hosting to rewriting URLs.
In your firebase.json file:
"hosting": {
"rewrites": [
{
"source": "/api/v1/your/path/here",
"function": "your_path_here"
}
]
}
Keep in mind this is a workaround and it has a major drawback: you will pay for double hit. Consider this if your app has to scale.
You can write your functions in different runtimes. The Node.js runtime uses the Express framework. So you can use its router to build different routes within a single function.
Add the dependency
npm install express#4.17.1
The following example is using typescript. Follow these guidelines to initiate a typescript project.
// index.ts
import { HttpFunction } from '#google-cloud/functions-framework';
import * as express from 'express';
import foo from './foo';
const app = express();
const router = express.Router();
app.use('/foo', foo)
const index: HttpFunction = (req, res) => {
res.send('Hello from the index route...');
};
router.get('', index)
app.use('/*', router)
export const api = app
// foo.ts
import { HttpFunction } from '#google-cloud/functions-framework';
import * as express from 'express';
const router = express.Router();
const foo: HttpFunction = (req, res) => {
res.send('Hello from the foo route...');
};
router.get('', foo)
export default router;
to deploy run:
gcloud functions deploy YOUR_NAME \
--runtime nodejs16 \
--trigger-http \
--entry-point api \
--allow-unauthenticated
Currently, in google allows only one event definition per function is supported. For more
Express can be installed with npm i express, then imported and used more or less as normal to handle routing:
const express = require("express");
const app = express();
// enable CORS if desired
app.use((req, res, next) => {
res.set("Access-Control-Allow-Origin", "*");
next();
});
app.get("/", (req, res) => {
res.send("hello world");
});
exports.example = app; // `example` is whatever your GCF entrypoint is
If Express isn't an option for some reason or the use case is very simple, a custom router may suffice.
If parameters or wildcards are involved, consider using route-parser. A deleted answer suggested this app as an example.
The Express request object has a few useful parameters you can take advantage of:
req.method which gives the HTTP verb
req.path which gives the path without the query string
req.query object of the parsed key-value query string
req.body the parsed JSON body
Here's a simple proof-of-concept to illustrate:
const routes = {
GET: {
"/": (req, res) => {
const name = (req.query.name || "world");
res.send(`<!DOCTYPE html>
<html lang="en"><body><h1>
hello ${name.replace(/[\W\s]/g, "")}
</h1></body></html>
`);
},
},
POST: {
"/user/add": (req, res) => { // TODO stub
res.json({
message: "user added",
user: req.body.user
});
},
"/user/remove": (req, res) => { // TODO stub
res.json({message: "user removed"});
},
},
};
exports.example = (req, res) => {
if (routes[req.method] && routes[req.method][req.path]) {
return routes[req.method][req.path](req, res);
}
res.status(404).send({
error: `${req.method}: '${req.path}' not found`
});
};
Usage:
$ curl https://us-east1-foo-1234.cloudfunctions.net/example?name=bob
<!DOCTYPE html>
<html lang="en"><body><h1>
hello bob
</h1></body></html>
$ curl -X POST -H "Content-Type: application/json" --data '{"user": "bob"}' \
> https://us-east1-foo-1234.cloudfunctions.net/example/user/add
{"message":"user added","user":"bob"}
If you run into trouble with CORS and/or preflight issues, see Google Cloud Functions enable CORS?

feathers.js -> Authentication token missing

I have a feathters.js application and now I want to secure the create and update hooks. I use a socket.io client and currently am going for JWT. I have added what I think I needed to add but am getting Error: Authentication token missing and Error Authenticating. The later I understand for that is from my code. I have a backend / frontend situation
So this is what I've implemented so far.
File: backend\backend.js (called in backend\index.js for the configuration of the app)
'use strict';
const path = require('path');
const serveStatic = require('feathers').static;
const favicon = require('serve-favicon');
const compress = require('compression');
const cors = require('cors');
const feathers = require('feathers');
const configuration = require('feathers-configuration');
const authentication = require('feathers-authentication');
const hooks = require('feathers-hooks');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const socketio = require('feathers-socketio');
const middleware = require('./middleware/index');
const services = require('./services/index');
const appFeathers = feathers();
appFeathers.configure(configuration(path.join(__dirname, '..')));
appFeathers.use(compress())
.options('*', cors())
.use(cors())
.use(favicon(path.join(appFeathers.get('public'), 'favicon.ico')))
.use('/', serveStatic(appFeathers.get('public')))
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: true}))
.configure(hooks())
.configure(rest())
.configure(socketio())
.configure(services)
.configure(middleware)
.configure(authentication());
module.exports = appFeathers;
File: backend\config\default.json
{
"host": "localhost",
"port": 3001,
"mysql_connection": "mysql://CONNECTION_STRING",
"public": "../public/",
"auth": {
"idField": "id",
"token": {
"secret": "SECRET_KEY"
},
"local": {}
}
}
In a working component of the frontend:
<template>
<div class="vttIndex">
idnex.vue
todo: eagle.js slideshow
todo: first info
<ul>
<li v-for="message in listMessages">
{{ message }}
</li>
</ul>
</div>
</template>
<script>
import feathers from 'feathers/client';
import socketio from 'feathers-socketio/client';
import hooks from 'feathers-hooks';
import io from 'socket.io-client';
import authentication from 'feathers-authentication/client';
import * as process from "../nuxt.config";
const vttSocket = io(process.env.backendUrl);
const vttFeathers = feathers()
.configure(socketio(vttSocket))
.configure(hooks())
.configure(authentication());
const serviceMessage = vttFeathers.service('messages');
vttFeathers.authenticate({
type: 'token',
'token ': 'SECRET_KEY'
}).then(function(result){
console.log('Authenticated!', result);
}).catch(function(error){
console.error('Error authenticating!', error);
});
export default {
layout: 'default',
data: function() {
return {
listMessages: []
}
},
mounted: function() {
serviceMessage.find().then(page => {
this.listMessages = page.data;
});
serviceMessage.on('created', (serviceMessage) => {
this.listMessages.push(serviceMessage);
});
}
}
</script>
As token, I have the secret key of the backend json file. As you see, now I only try to log console messages. It is doing something for my error message is coming from there.
Question
Where am I missing what to have this functioning?
Goal
Just in case it's needed. My goal is for all 'public' data to be select with a token in my client and then an admin section maybe with 0auth. So the general 'SELECT' stuff is secured through a token instead of no authentication at all.
Solution
Okay I solved it, sort of. I first needed to create a user. Then I needed to do a local login with the user. That returns a token. If I use that, then there is no problem at all.
To use a token, you must first make sure it is generated. I was using the secret key as token what isn't correct. When you first athenticate with the 'local' type (default email and password) it will create a token and that is what you could then use with the method 'token'

How to use fast-json-patch in Angular 2 applications?

I want to use the "fast-json-patch" library (https://github.com/Starcounter-Jack/JSON-Patch) in an Angular 2 application.
I have tried adding:
'fast-json-patch': 'vendor/fast-json-patch/dist/json-patch-duplex.min.js'
in the system-config.ts file under the map but it doesn't work when importing fast-json-patch
1) Install the package
npm install fast-json-patch --save
2) In the component, where you want to use ist, import the functions you need:
import { compare } from 'fast-json-patch';
3) To create a Patch compare the old object with the new object:
const patch = compare(oldObj, modifiedObj);
4) Print out the result:
console.log(patch);
0:{op: "replace", path: "/firmendetails/registergericht", value: "Darmstadt xx"}
1:{op: "remove", path: "/firmendetails/handelsname"}
2:{op: "remove", path: "/firmendetails/firma"}
3:{op: "remove", path: "/firmendetails/rechtsform"}
This is how my system-config.ts file looks like:
import * as express from 'express';
import {ng2engine} from 'angular2-universal-preview';
// Angular 2
import {App} from './src/app';
let app = express();
// Express View
app.engine('.ng2.html', ng2engine);
app.set('views', __dirname);
app.set('view engine', 'ng2.html');
// static files
app.use(express.static(__dirname));
app.use('/', (req, res) => {
res.render('index', { App });
});
app.listen(3000, () => {
console.log('Listen on http://localhost:3000');
});
Please add your code, so I can take a look?