proxy a request on docusaurus - node.js

// #ts-check
// Note: type annotations allow type checking and IDEs autocompletion
const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');
/** #type {import('#docusaurus/types').Config} */
const config = {
title: 'title',
tagline: 'tag,
url: 'some-utl',
baseUrl: '/',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
organizationName: 'facebook', // Usually your GitHub org/user name.
projectName: 'project', // Usually your repo name.
plugins: [
[
'docusaurus-plugin-openapi',
{
id: 'api',
path: './openapi.json',
routeBasePath: '/api',
},
],
],
presets: [
[
'docusaurus-preset-openapi',
/** #type {import('docusaurus-preset-openapi').Options} */
({
api: {
path: './openapi.json',
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
proxy: {
'/api': {
target: 'http://localhost:3000',
},
},
}),
],
],
themeConfig:
/** #type {import('docusaurus-preset-openapi').ThemeConfig} */
({
navbar: {
title: 'title',
logo: {
alt: 'My Site Logo',
src: 'img/logo.svg',
},
items: [{ to: '/api', label: 'API', position: 'left' }],
},
prism: {
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
},
}),
};
module.exports = config;
This is my code for the docusaurus config file but some how the proxy doesn't work

Related

You don't have permission to access this resource. nuxt npm run generate

In nuxt project, when you refer to an address other than the main address, you will see this message.
(Keep in mind that this does not happen when you are in the app and move to other pages, and only happens when you directly enter the address in the url of the browser!
Can it be from standalone method?)
For example:
cpalizade.ir | is ok
cpalizade.ir/login | not ok(forbidden)
It should be noted that this happens in projects where we use
run generate
and upload dist file in public_html.
but it will not happen when we use
run build
my nuxt.config.js:
import colors from 'vuetify/es5/util/colors'
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
titleTemplate: 'Cp Alizade',
title: 'Cp Alizade',
meta: [{
charset: 'utf-8'
},
{name: "msapplication-TileColor", content: "#da532c"},
{name: "theme-color", content: "#ffffff"},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
},
{
name: 'apple-mobile-web-app-capable',
content: 'yes'
},
{
name: 'apple-mobile-web-app-status-bar-style',
content: 'default'
},
{
hid: 'description',
name: 'description',
content: ''
},
],
link: [
{rel: "apple-touch-icon", sizes: "180x180", href: "/apple-touch-icon.jpg"},
{rel: "icon", type: "image/png", sizes: "32x32", href: "/favicon.png"},
{rel: "icon", type: "image/png", sizes: "16x16", href: "/favicon.png"},
{rel: "manifest", href: "/site.webmanifest"},
{rel:"mask-icon", href: "/safari-pinned-tab.svg", color: "#5bbad5"},
],
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: [
'#/assets/css/main.scss',
'#mdi/font/css/materialdesignicons.min.css'
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
// {
// src: '#/plugins/swiper.js',
// mode: 'client'
// },
// {src: '~/plugins/chart.js', mode: 'client'},
{
src: '#/plugins/vuelidate.js'
},
{
src: '#/plugins/pouchdb.js',
mode: 'client'
},
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/vuetify
['#nuxtjs/vuetify', {
rtl: true,
iconfont: 'mdi'
}],
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
'nuxt-leaflet',
],
auth: {
redirect: {
login: '/login',
logout: '/login',
callback: '/login',
home: '/'
},
strategies: {
local: {
scheme: 'local',
token: {
property: 'access_token',
required: true,
type: 'Bearer'
},
user: {
property: false, // <--- Default "user"
autoFetch: true
},
endpoints: {
login: {
url: 'https://api.cpalizade.ir/api/' + 'users/login',
method: 'post'
},
logout: {
url: 'https://api.cpalizade.ir/api/' + 'users/logout',
method: 'post'
},
user: {
url: 'https://api.cpalizade.ir/api/' + 'user',
method: 'get'
}
}
},
phone: {
scheme: 'local',
token: {
property: 'access_token',
required: true,
type: 'Bearer'
},
user: {
property: false, // <--- Default "user"
autoFetch: true
},
endpoints: {
login: {
url: 'https://api.cpalizade.ir/api/' + 'users/login-w-otp',
method: 'post'
},
logout: {
url: 'https://api.cpalizade.ir/api/' + 'users/logout',
method: 'post'
},
user: {
url: 'https://api.cpalizade.ir/api/' + 'user',
method: 'get'
}
}
}
}
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
// See https://github.com/nuxt-community/axios-module#options
baseURL: 'https://api.cpalizade.ir/api/',
credentials: false,
proxy: false,
debug: true,
retry: {
retries: 0
},
requestInterceptor: (config, {
store
}) => {
config.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;application/json';
config.headers.common['Access-Control-Allow-Origin'] = '*';
return config
}
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
name: 'Cp Alizade',
short_name: 'Cp Alizade',
lang: 'fa',
theme_color: '#222',
background_color: '#222',
start_url: `/`,
prefer_related_applications: true,
},
icon: {
fileName: 'favicon.png'
},
},
// Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify
vuetify: {
customVariables: ['~/assets/variables.scss'],
defaultAssets: false,
theme: {
dark: false,
themes: {
light: {
primary: '#1938d3',
secondary: '#ff2626',
info:'#1867c0',
jozi: '#45c235'
},
dark: {
primary: '#1938d3',
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: '#DF382C',
success: colors.green.accent3
}
}
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
extend(config, ctx) {
} // blah blah
}
}
.htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
DirectoryIndex 200.html
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /200.html [L]

Change an array loaded from another component in React.js jsx

I am trying to change a hardcoded array within another JSX file.
the first file routes.js. I tried loading the array then changing it . it just changes the loaded data not the array directly from the other file. How do i write to the other JSX array from the main component.
const routes = [
{
type: "collapse",
name: "Our Mission",
key: "dashboards",
icon: <Shop size="12px" />,
collapse: [
{
name: "Ways We can Help",
key: "default",
route: "/dashboards/default",
component: Default,
},
{
name: "How It Works",
key: "automotive",
route: "/dashboards/automotive",
component: Automotive,
},
{
name: "Who We Are",
key: "smart-home",
route: "/dashboards/smart-home",
component: SmartHome,
},
],
},
{ type: "title", title: " ", key: "space1" },
{
type: "collapse",
name: "Services",
key: "services",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
{
type: "collapse",
name: "Products",
key: "products",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
];
export default routes;
code used in main jsx file. I want to be able to write to the remote array changing its values.
const handleSubmit = (event) => {
event.preventDefault();
// I want to push or filter with the code below
{
routes.length = 0;
routes.map((route) => console.log({ route }));
}
};
You can't change the array itself because it's a const. You could change it to a let and then export it like this:
EDIT
export let routes = [
{
type: "collapse",
name: "Our Mission",
key: "dashboards",
icon: <Shop size="12px" />,
collapse: [
{
name: "Ways We can Help",
key: "default",
route: "/dashboards/default",
component: Default,
},
{
name: "How It Works",
key: "automotive",
route: "/dashboards/automotive",
component: Automotive,
},
{
name: "Who We Are",
key: "smart-home",
route: "/dashboards/smart-home",
component: SmartHome,
},
],
},
{ type: "title", title: " ", key: "space1" },
{
type: "collapse",
name: "Services",
key: "services",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
{
type: "collapse",
name: "Products",
key: "products",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
];
Then to use it in another jsx component you can import it like this.
import {routes} from '../yourPathToIt/main'

Next JS advanced feature Content Security policy format

I am adding security Policy headers to my application using Security headers advanced feature of next.js
Reference :https://nextjs.org/docs/advanced-features/security-headers
I am quiet clear of how to add the security policies to the next application except the Content Security policy,It does not show any format of the policy in the Documentation :
Taking help of next and developer.mozilla org I have some code in place,that I am attaching herewith. Can anybody help me with the correct format to define content-security policy in Next.JS
Code in Next.config.js
const cspPolicy = "default-src 'self';connect-src 'self','preview.contentful.com','*.flippenterprise.net', 'aq.flippenterprise.net','https://www.google-analytics.com','dpm.demdex.net','stats.g.doubleclick.net','lcljoefresh.sc.omtrdc.net','sfml.flippback.com','p.flipp.com','https://sentry.io/',";
const securityHeaders = [
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
},
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
},
{
key: 'Content-Security-Policy',
value: cspPolicy
}
];
const headers = {
async headers() {
return [
{
// Apply these headers to all routes in your application.
source: '/(.*)',
headers: securityHeaders,
},
]
},
}
const nextConfig = {
env: {
search_key: process.env.search_key,
appDynamicsKey: process.env.appDynamicsKey,
ENVIRONMENT: process.env.ENVIRONMENT,
},
webpack5:false,
// https://nextjs.org/docs#customizing-webpack-config
webpack: (webpackConfig) => {
const { module = {} } = webpackConfig;
return {
...webpackConfig,
module: {
...module,
rules: [
...(module.rules || []),
{
test: /\.(txt|png|woff|woff2|eot|ttf|gif|jpg|ico|svg)$/,
use: {
loader: 'file-loader',
options: {
name: '[name]_[hash].[ext]',
publicPath: '/_next/static/files',
outputPath: 'static/files',
},
},
},
{
test: /\.spec.jsx$/,
loader: 'ignore-loader',
},
],
},
};
},
};
const sassOptions = {
sassLoaderOptions: {
outputStyle: 'compressed',
},
};
module.exports = withPlugins(
[[withSass, sassOptions], [withFonts], [withCSS], [withBundleAnalyzer]],
nextConfig,
headers,
);

Upgrade of Webpack 1 to 4 got so complicated

I have been stuck with this upgrade since 2 days and I have made some progress.
It is an old project and I have to take it a bit forward.
This is my webpack.config.js file:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
//const validate = require('webpack-validator');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const PATHS = {
app: path.join(__dirname, 'src/js'),
build: path.join(__dirname, 'build'),
public: path.join(__dirname, 'src/public'),
assets: path.join(__dirname, 'src/assets'),
styles: [
path.join(__dirname, 'src/assets/css/bootstrap.min.css'),
path.join(__dirname, 'src/assets/css/font-awesome.min.css'),
path.join(__dirname, 'src/assets/css/bootstrap-grid-rtl.css'),
path.join(__dirname, 'src/assets/css/main.css'),
path.join(__dirname, 'src/assets/css/PrintStyle.css'),
path.join(__dirname, 'node_modules/react-dates/lib/css/_datepicker.css'),
path.join(__dirname, 'node_modules/flag-icon-css/css/flag-icon.css'),
path.join(__dirname, 'src/assets/css/react-datepicker.css'),
path.join(__dirname, 'src/assets/css/tracker.css'),
]
};
const isDebug = !process.argv.includes('--release');
module.exports = {
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true
},
sourceMap: true
})
],
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
}
}
},
entry: {
app: ['babel-polyfill',PATHS.app],
style: PATHS.styles
},
output: {
path: PATHS.build,
filename: 'js/[name].js',
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx?$/,
use:
{
loader: 'babel-loader'
}
,
include: [
path.resolve(__dirname, PATHS.app),
],
query: {
cacheDirectory: isDebug,
babelrc: true,
presets: ['latest', 'react',
...isDebug ? [] : [
'react-optimize',
],
],
plugins: [
'transform-object-rest-spread',
'transform-object-assign',
[
'react-intl', {
'messagesDir': './build/messages',
'enforceDescriptions': false
}
]
]
},
},
{
test: /\.css$/,
use:
{
loader: ExtractTextPlugin.extract(
'style-loader',
`css-loader?${JSON.stringify({
importLoaders: 1,
sourceMap: true,
modules: true,
localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
discardComments: { removeAll: true },
})}`,
'resolve-url-loader',
'postcss-loader?pack=default'
)
}
,
exclude: PATHS.styles,
},
{
test: /\.css$/,
use: [
{
loader:
ExtractTextPlugin.extract(
'style-loader',
`css-loader?${JSON.stringify({
localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
minimize: true,
discardComments: { removeAll: true },
})}`,
'resolve-url-loader'
)
}
],
exclude: PATHS.app,
include: PATHS.styles
},
{
test: /\.sss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
{
test: /\.json$/,
use: [
{
loader: 'json-loader'
}
]
},
{
test: /\.(eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
use: [
{
loader:
`file-loader?${JSON.stringify({
name: isDebug ? '/[path][name].[ext]?[hash:8]' : '/fonts/[hash:8].[ext]',
})}`
}
]
},
{
test: /\.(ico|jpg|jpeg|png|gif)(\?.*)?$/,
use: [
{
loader:
`file-loader?${JSON.stringify({
name: isDebug ? '/[path][name].[ext]?[hash:8]' : '/images/[hash:8].[ext]'
})}`
}
]
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
'process.env.BROWSER': true,
__DEV__: isDebug,
}),
new ExtractTextPlugin('[name].css', {allChunks: true}),
new OptimizeCssAssetsPlugin({
cssProcessorOptions: { discardComments: {removeAll: true } },
}),
new HtmlWebpackPlugin({
title: 'GACA Portal',
template: path.join(PATHS.public, 'index.ejs'),
favicon: path.join(PATHS.assets, 'images/favicon.ico'),
}),
...isDebug? [
new webpack.HotModuleReplacementPlugin({
multiStep: true
}),
] : [
new CleanWebpackPlugin(PATHS.build, {
root: process.cwd()
}),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.DedupePlugin()
] //else ends
],
// Don't attempt to continue if there are any errors.
bail: !isDebug,
cache: false,
stats: {
colors: true,
reasons: isDebug,
timings: true,
},
devtool: isDebug ? 'cheap-module-source-map' : false,
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
stats: 'errors-only',
port: 3000,
host: '0.0.0.0',
publicPath: '/',
contentBase: PATHS.build,
proxy: {
'/api/**': {
target: 'http://localhost:8080',
secure: false
}
}
},
/*postcss: [
require('postcss-partial-import')(),
require('postcss-url')(),
require('postcss-custom-properties')(),
require('postcss-custom-media')(),
require('postcss-media-minmax')(),
require('postcss-custom-selectors')(),
require('autoprefixer')({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
})
]*/
};
Now I am trying to npm start but I still getting this error:
× 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module.rules[2].use should be one of these:
non-empty string | function | object { ident?, loader?, options?, query? } | function | [non-empty string | function | object { ident?, loader?, options?, query? }]
-> Modifiers applied to the module when rule is matched
Details:
* configuration.module.rules[1].use should be a string.
* configuration.module.rules[1].use should be an instance of function
* configuration.module.rules[1].use.loader should be a string.
* configuration.module.rules[1].use should be an instance of function
* configuration.module.rules[1].use should be an array:
[non-empty string | function | object { ident?, loader?, options?, query? }]
* configuration.module.rules[2].use should be a string.
* configuration.module.rules[2].use should be an instance of function
* configuration.module.rules[2].use should be an object.
* configuration.module.rules[2].use should be an instance of function
* configuration.module.rules[2].use[0] should be a string.
* configuration.module.rules[2].use[0] should be an instance of function
* configuration.module.rules[2].use[0].loader should be a string.
- configuration.resolve.extensions[0] should not be empty.
Any help would be very helpful
Here is a step by step guide from Webpack.
https://webpack.js.org/migrate/
If you have plugin which is not provided by webpack, please go and check on the repo.
I'd recommend first upgrading to version 2 or 3 https://webpack.js.org/migrate/3/ , you will have clear documentation and you will find great help in Google ...
And only then continue to version 4 https://webpack.js.org/migrate/4/
I just left it away and create a new project with create app cli and copied the content and formatted the structure

How use "html-webpack-plugin" and "CommonsChunkPlugin"?

I use CommonsChunkPlugin in my project, wash it can peel public-code
new Wp.optimize.CommonsChunkPlugin({
name: 'library',
minChunks:2,
}),
but, When I use html-webpack-plugin render html, The html-result has not include public-code.
This is my webpack.config.js
//webpack.config.js
var Path =require('path');
var Wp =require('webpack');
var ETWP =require('extract-text-webpack-plugin');
var HWP = require('html-webpack-plugin');
var eSCSS = new ETWP('css/[name].css');
module.exports ={
entry :{
indexApp: Path.resolve(__dirname ,'./src/js/index.js'),
aboutApp: Path.resolve(__dirname ,'./src/js/about.js'),
},
output :{
path :'./lib/',
filename :'js/[name].js',
},
module :{
loaders :[
{
test: /\.scss$/i,
loader: eSCSS.extract(['css','sass']),
},
],
},
plugins :[
new HWP({
filename: './about.html',
template: './src/tpl/about.html',
chunks:["aboutApp","library.js"],
xhtml: true,
inject: true,
}),
new HWP({
filename: './index.html',
template: './src/tpl/index.html',
chunks:["indexApp"],
xhtml: true,
inject: true,
}),
new Wp.optimize.CommonsChunkPlugin({
name: 'library',
minChunks:2,
}),
};
How can I conrfig?
Thinks.

Resources