access angular route in nodejs app on heroku - angularjs

I am trying to host an angularjs project on Heroku. App works just fine on local and when running heroku local web.
But when trying to access, I am getting error TypeError: response.sendFile is not a function.
Server.js
//Load HTTP module
var express = require('express');
const app = express();
var http = require("http");
var port = process.env.PORT|| 8000 ;
//Create HTTP server and listen on port 8000 for requests
http.createServer(function (request, response) {
// Set the response HTTP header with HTTP status and Content type
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body "Hello World"
response.end('Hello World\n');
response.sendFile('views/main.html' , { root : __dirname});
console.log(__dirname);
}).listen(port);
// Catch all other routes and return the index file
app.use(express.static(__dirname + '/views'));
app.get('/',function(req, res){
res.sendFile('views/main.html' , { root : __dirname});
});
console.log("\n\n\n"+__dirname+"Hello\n\n\n\n"); // prints /app in node
console
console.log("\n\n"+process.version+"\n\n\n\n"); // v6.10.2
// Print URL for accessing server
console.log('Server running at '+port);
Package.json
{
"name": "startup",
"private": true,
"devDependencies": {
"#angular/cli": "^1.4.7",
"#angular/compiler-cli": "^4.4.0",
"bower": "1.8.0",
"typescript": "^2.3.4",
"graceful-fs": "^4.1.11",
"gulp": "^3.9.0",
"gulp-autoprefixer": "^2.3.1",
"gulp-cache": "^0.2.10",
"gulp-connect": "^2.3.1",
"gulp-filter": "^2.0.2",
"gulp-imagemin": "^2.3.0",
"gulp-jshint": "^1.12.0",
"gulp-karma": "0.0.4",
"gulp-load-plugins": "^0.10.0",
"gulp-minify-css": "^1.2.0",
"gulp-ng-annotate": "^1.0.0",
"gulp-plumber": "^1.0.1",
"gulp-rev": "^5.0.1",
"gulp-rev-replace": "^0.4.2",
"gulp-uglify": "^1.2.0",
"gulp-useref": "^3.0.0",
"gulp-util": "^3.0.6",
"gulp-watch": "^4.2.4",
"jasmine-core": "^2.7.0",
"jshint": "^2.9.5",
"jshint-stylish": "^1.0.0",
"karma": "^1.7.0",
"karma-chrome-launcher": "^2.2.0",
"karma-jasmine": "^1.1.0",
"karma-phantomjs-launcher": "^1.0.4",
"lazypipe": "^0.2.4",
"minimatch": "^3.0.4",
"open": "0.0.5",
"phantomjs-prebuilt": "^2.1.16",
"rimraf": "^2.4.0",
"run-sequence": "^1.1.1",
"wiredep": "^2.2.2"
},
"engines": {
"node": "6.10.2"
},
"dependencies": {
"body-parser": "~1.5.2",
"express": "^4.8.0",
"gulp-bower-fix-css-path": "^0.1.1",
"gzippo": "^0.2.0",
"method-override": "~2.1.2",
"mongoose": "^4.12.4"
},
"scripts": {
"start": "gulp serve"
},
"description": "This project is generated with [yo angular generator](https://github.com/yeoman/generator-angular) version 0.16.0.",
"version": "1.0.0",
"main": "gulpfile.js",
"directories": {
"test": "test"
},
"repository": {
"type": "git",
"url": "1.0.0"
},
"author": "",
"license": "ISC"
}
Few points :
1. node version is "6.10.2"
2. express version is "^4.8.0"
3. res.sendFile with uppercase F or res.sendfile with lowercase f, nothing works.

What build pack are you using on heroku? Is it possible that you have an old version of express in heroku's npm cache? Try heroku config:set NODE_MODULES_CACHE=false and push a change to force a rebuild.
Also note that sendFile is present twice in your code so have you tried to replace it with sendfile at both places.

Resolved.
Instead of http.createServer(function (request, response) {} block, I added app.listen(port);

Related

How can I deploy Vite app that uses MERN stact to Render.com?

I have been trying to get my MERN app to run on Render, but I cannot get it to work.
root
backend
server.js
controllers
middleware
models
routes
package.json
public
src
package.json
I dont know if I structured it incorrectly. Here is the package.json in "backend"
{
"name": "supportsys",
"private": true,
"version": "0.0.0",
"type": "commonjs",
"scripts": {
"dev": "concurrently \"vite\" \"npm run server\"",
"build": "vite build",
"preview": "vite preview",
"start": "node server.js",
"server": "nodemon server.js"
},
"dependencies": {
"#reduxjs/toolkit": "^1.9.1",
"axios": "^1.2.2",
"bcryptjs": "^2.4.3",
"colors": "^1.4.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.8.2",
},
"devDependencies": {
"#import-meta-env/unplugin": "^0.4.1",
"#types/react": "^18.0.26",
"#types/react-dom": "^18.0.9",
"#vitejs/plugin-react": "^3.0.0",
"autoprefixer": "^10.4.13",
"nodemon": "^2.0.20",
"postcss": "^8.4.20",
"tailwindcss": "^3.2.4",
"vite": "^4.0.0"
},
"main": "server.js",
"author": "",
"license": "ISC",
"description": ""
}
This is the package.json in my root folder
{
"name": "supportsys",
"private": true,
"version": "0.0.0",
"type": "commonjs",
"scripts": {
"dev": "concurrently \"vite\" \"npm run server\"",
"build": "vite build",
"preview": "vite preview",
"start": "node backend/server.js",
"server": "nodemon backend/server.js"
},
"dependencies": {
"#reduxjs/toolkit": "^1.9.1",
"axios": "^1.2.2",
"bcryptjs": "^2.4.3",
"colors": "^1.4.0",
"concurrently": "^7.6.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.8.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.7.1",
"react-modal": "^3.16.1",
"react-redux": "^8.0.5",
"react-router-dom": "^6.6.1",
"react-toastify": "^9.1.1",
"redux": "^4.2.0",
"redux-devtools-extension": "^2.13.9"
},
"devDependencies": {
"#import-meta-env/unplugin": "^0.4.1",
"#types/react": "^18.0.26",
"#types/react-dom": "^18.0.9",
"#vitejs/plugin-react": "^3.0.0",
"autoprefixer": "^10.4.13",
"nodemon": "^2.0.20",
"postcss": "^8.4.20",
"tailwindcss": "^3.2.4",
"vite": "^4.0.0"
},
"main": "",
"author": "",
"license": "ISC",
"description": ""
}
My server.js file
const express = require("express");
require("dotenv").config();
const colors = require("colors");
const path = require("path");
const app = express();
var cors = require("cors");
app.use(cors());
const port = process.env.PORT || 9000;
const errorHandler = require("./middleware/errorMiddleware");
const connectDB = require("./config/db");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
connectDB();
if (process.env.NODE_ENV === "production") {
// Set build folder as static
app.use(express.static(path.join(__dirname, "../build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../index.html"));
});
} else {
app.get("/", (req, res) => {
res.status(200).json({ message: "Welcome to the API" });
});
}
app.use("/api/users", require("./routes/userRoutes"));
app.use("/api/tickets", require("./routes/ticketRoutes"));
app.use(errorHandler);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
I would appreciate if someone could point me towards a direction. I cannot possibly manage to host my backend as webservice, static site runs fine but backend is not there.
I deployed my backend to render and when I deploy my backend i get this error on console "Loading failed for the module with source “https://sys-ctzx.onrender.com/src/main.jsx”."

Gatsby, Prismic - error Building static HTML failed for path "/blog/"

I have a website created using Gatsby v. 3.0.1 and Prismic CMS, and Github Actions for CI/CD. The build of the page on GH is triggered automatically every time content is added/edited on CMS.
Blog posts on the website are generated dynamically with gatsby-node.js createPage function:
const blog = require.resolve(
`./src/components/features/blog/post/PostDetails.tsx`
);
const result = await graphql(`
{
allPrismicBlogPost {
edges {
node {
lang
tags
data {
link {
text
}
}
}
}
}
}
`);
result?.data?.allPrismicBlogPost?.edges?.forEach(({ node }) => {
createPage({
path: `/blog/${node?.data?.link?.text}/`,
component: blog,
context: {
link: node?.data?.link?.text,
},
});
});
Couple of days ago after adding a new blog post the build failed with following error:
error Building static HTML failed for path "/blog/"
SyntaxError:Unexpected number in JSON at position 183
- JSON.parse
- render-html.js:58 readPageData
[website]/[gatsby]/dist/utils/worker/render-html.js:58:15
- render-html.js:266 async _bluebird.default.map.concurrency
[website]/[gatsby]/dist/utils/worker/render-html.js:266:24
Now every time I try to add new post the build fails, and the only way to fix this is to archive the post in Prismic. Weird thing is that this build fail doesn't happen if I edit already existing blog post, only when adding a new one.
I cannot reproduce the error locally, it only fails on Github build.
I've already looked through the blog post in order to find something that could've broken the build, like some unusual fields that weren't present in previous blog posts, reinstalled all packages, updated package-lock.json, added empty blog posts to see if this would work, looked through every file in /public folder to find some clue but nothing yet worked and the build still fails when adding new blog posts. Has anyone else had this issue and knows how to fix this?
Full stack trace:
https://pastebin.com/VbLJZk3P
My package.json:
{
"name": "gatsby-starter-default",
"private": true,
"description": "A simple starter to get up and developing quickly with Gatsby",
"version": "0.1.0",
"author": "Kyle Mathews <mathews.kyle#gmail.com>",
"dependencies": {
"-": "^0.0.1",
"#reduxjs/toolkit": "^1.5.0",
"#types/react-redux": "^7.1.16",
"#types/styled-components": "^5.1.9",
"bootstrap": "^4.6.0",
"dotenv": "^8.2.0",
"gatsby": "^3.0.1",
"gatsby-plugin-alias-imports": "^1.0.5",
"gatsby-plugin-force-trailing-slashes": "^1.0.5",
"gatsby-plugin-gatsby-cloud": "^2.0.0",
"gatsby-plugin-gdpr-cookies": "^2.0.8",
"gatsby-plugin-graphql-codegen": "^3.1.0",
"gatsby-plugin-manifest": "^3.0.0",
"gatsby-plugin-offline": "^4.0.0",
"gatsby-plugin-react-helmet": "^4.0.0",
"gatsby-plugin-react-svg": "^3.0.0",
"gatsby-plugin-robots-txt": "^1.6.10",
"gatsby-plugin-sass": "^4.1.0",
"gatsby-plugin-sharp": "^3.0.0",
"gatsby-plugin-sitemap": "^4.10.0",
"gatsby-plugin-social9-socialshare": "^1.0.5",
"gatsby-source-filesystem": "^3.0.0",
"gatsby-source-prismic": "^3.3.4",
"gatsby-transformer-sharp": "^3.0.0",
"graphql": "^15.5.0",
"graphql-cli": "3.0.14",
"graphql-request": "^3.4.0",
"prismic-reactjs": "^1.3.3",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-bootstrap": "^1.5.2",
"react-cookie-consent": "^6.2.4",
"react-dom": "^17.0.1",
"react-glider": "^2.1.1",
"react-helmet": "^6.1.0",
"react-is": "^17.0.2",
"react-media": "^2.0.0-rc.1",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"redux": "^4.0.5",
"sass": "^1.32.8",
"styled-components": "^5.2.3",
"uuid": "^8.3.2"
},
"devDependencies": {
"#types/node": "^14.14.35",
"#types/react": "^17.0.3",
"#types/react-dom": "^17.0.2",
"#types/react-helmet": "^6.1.0",
"#types/uuid": "^8.3.4",
"eslint-config-prettier": "^8.3.0",
"prettier": "^2.2.1",
"tsconfig-paths-webpack-plugin": "^3.5.1",
"typescript": "^4.2.3"
},
"keywords": [
"gatsby"
],
"license": "0BSD",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
"start": "npm run develop",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "npm run type-check && npm run lint",
"lint": "eslint . --ext .ts,.tsx",
"type-check": "tsc --pretty"
},
"repository": {
"type": "git",
"url": "https://github.com/gatsbyjs/gatsby-starter-default"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
}
}

Setup Jest Debug with a monorepo Create-React-App with TypeScript and VSCode

I've been hitting my head for about 7 hours now. But this is paramount as I can't afford not to develop tests within the app any further (Currently stuck debugging an Apollo React test)
I'm currently under a monorepo with a shared repository and 2 create-react app. I'm using CRACO (Create-React-App Configure Override), and I can't seem to execute a debugging statement using VScode. I've faced numerous issues: malformed jest commands, transformation problems (css modules not being parsed correctly), hung-up vscode, not found scripts, and many more. I'm stuck and I don't know what else to do.
The monorepo is setup using plain yarn workspaces (no Lerna nor bolt or pmp). It has a shared component (with storybook) and 2 create-react apps (app and home respectively). CRACO is used to apply the babel-loader to the shared component repo.
I'm able to run the tests with yarn: cross-env SKIP_PREFLIGHT_CHECK=true CI=true craco test --env=jest-environment-jsdom-sixteen --maxWorkers=4 --transformIgnorePatterns \"node_modules/(?!date-fns)/\", but I haven't been able to either use the traditional debugging or using The Jest Runner vscode extension which is what I want to run specific tests (currently only in the app folder).
Here's my monorepo structure
These are some of the methods that I've tried:
Here are some of the links that I've visited and tried.
https://www.basefactor.com/using-visual-studio-code-to-debug-jest-based-unit-tests
https://github.com/firsttris/vscode-jest-runner
https://github.com/jest-community/vscode-jest/issues/129
https://github.com/jest-community/vscode-jest/issues/244
https://dev.to/shnydercom/monorepos-lerna-typescript-cra-and-storybook-combined-4hli
And many, many more.
I've also tried exporting the jest config using craco and pointing it to the path... nada.
Main (root) package.json
{
"name": "schon",
"version": "0.1.0",
"private": true,
"reactSnap": {
"inlineCss": true
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"dependencies": {
"#apollo/client": "^3.3.4",
"#auth0/auth0-react": "^1.2.0",
"#date-io/date-fns": "1.3.13",
"#material-ui/core": "4.11.1",
"#material-ui/icons": "4.9.1",
"#material-ui/lab": "^4.0.0-alpha.55",
"#material-ui/pickers": "^3.2.10",
"#material-ui/system": "4.9.14",
"#nivo/calendar": "0.67.0",
"#nivo/core": "0.67.0",
"#nivo/line": "0.67.0",
"#nivo/tooltip": "^0.67.0",
"#reach/router": "^1.3.3",
"#snowpack/app-scripts-react": "^2.0.0",
"auth0-js": "^9.13.2",
"aws-appsync-auth-link": "^2.0.3",
"aws-sdk": "^2.714.0",
"clsx": "^1.1.1",
"date-fns": "^2.14.0",
"dotenv": "^8.2.0",
"exceljs": "^4.2.0",
"file-saver": "^2.0.2",
"formik": "^2.1.4",
"formik-persist": "^1.1.0",
"graphql": "^15.0.0",
"immer": "^6.0.9",
"linkifyjs": "^2.1.9",
"lodash": "^4.17.15",
"logrocket": "^1.0.7",
"material-table": "^1.59.0",
"msw": "^0.24.2",
"randomcolor": "^0.6.2",
"react": "17.0.1",
"react-apollo": "^3.1.5",
"react-dom": "17.0.1",
"react-elastic-carousel": "^0.6.4",
"react-error-boundary": "^2.2.1",
"react-hook-form": "^6.3.0",
"react-loading-skeleton": "^2.1.1",
"react-prerendered-component": "^1.2.4",
"react-scripts": "4.0.1",
"snowpack": "^3.0.11",
"styled-components": "^5.2.1",
"suneditor": "^2.35.0",
"suneditor-react": "^2.13.1",
"sw-precache": "^5.2.1",
"tiny-slider-react": "^0.4.0",
"uglifyjs": "^2.4.11",
"uuid": "^8.2.0",
"validate-password": "^1.0.4",
"xlsx": "^0.16.1",
"yup": "^0.29.1"
},
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/helper-create-regexp-features-plugin": "^7.10.4",
"#craco/craco": "6.1.1",
"#react-theming/storybook-addon": "^1.0.3",
"#storybook/addon-actions": "^6.1.19",
"#storybook/addon-docs": "^6.1.19",
"#storybook/addon-essentials": "^6.1.19",
"#storybook/addon-knobs": "^6.1.19",
"#storybook/addon-links": "^6.1.19",
"#storybook/addon-storysource": "^6.1.19",
"#storybook/node-logger": "^6.1.19",
"#storybook/preset-create-react-app": "^3.1.6",
"#storybook/react": "^6.1.19",
"#testing-library/dom": "^7.29.0",
"#testing-library/jest-dom": "^5.11.1",
"#testing-library/react": "^11.2.2",
"#testing-library/user-event": "^12.5.0",
"#types/auth0-js": "^9.13.1",
"#types/file-saver": "^2.0.1",
"#types/jest": "^26.0.16",
"#types/linkifyjs": "^2.1.3",
"#types/lodash": "^4.14.154",
"#types/memoize-one": "^5.1.2",
"#types/node": "^14.0.6",
"#types/randomcolor": "^0.5.5",
"#types/reach__router": "^1.3.5",
"#types/react": "17.0.0",
"#types/react-dom": "17.0.0",
"#types/tiny-slider-react": "^0.3.2",
"#types/uuid": "^8.0.0",
"#types/yup": "^0.29.1",
"#typescript-eslint/eslint-plugin": "^4.9.0",
"#typescript-eslint/parser": "^4.9.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.1.0",
"bolt": "^0.24.5",
"cross-env": "^7.0.2",
"dynamic-cdn-webpack-plugin": "^5.0.0",
"eslint-config-airbnb-typescript": "^12.0.0",
"eslint-config-prettier": "^6.15.0",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-prettier": "^3.2.0",
"eslint-plugin-react": "^7.21.5",
"gulp": "^4.0.2",
"gulp-json-editor": "^2.5.4",
"gulp-replace": "^1.0.0",
"html-webpack-plugin": "^4.5.0",
"husky": "^4.3.0",
"jest-axe": "^3.4.0",
"jest-canvas-mock": "^2.3.0",
"jest-dom": "^4.0.0",
"jest-environment-jsdom-sixteen": "^1.0.3",
"lint-staged": "^10.5.2",
"microbundle": "^0.12.3",
"prettier": "2.0.5",
"react-is": "^16.13.1",
"react-snap": "^1.23.0",
"source-map-explorer": "^2.4.2",
"storybook-addon-material-ui": "^0.9.0-alpha.24",
"ts-jest": "^26.5.2",
"typescript": "4.1.2",
"uglify": "^0.1.5",
"webpack-cdn-plugin": "^3.3.1"
},
"bolt": {
"workspaces": [
"./app",
"./home",
"./components"
]
},
"workspaces": [
"./app",
"./home",
"./components"
]
}
app package.json:
{
"name": "app",
"version": "0.1.0",
"private": true,
"scripts": {
"circular-deps": "ts-node ccd.ts",
"analyze": "source-map-explorer 'build/static/js/*.js'",
"start-snowpack-not-working": "snowpack dev --config snowpack.config.js",
"start": "craco start --host 0.0.0.0",
"build": "cross-env SKIP_PREFLIGHT_CHECK=true NODE_OPTIONS=--max_old_space_size=4096 craco build && yarn run build-snap && yarn run enable-sw",
"build-snap": "react-snap && npm run generate-sw",
"enable-sw": "gulp snap-off",
"format": "prettier --write src/**/*.ts{,x}",
"lint": "eslint --ext .ts --ext .tsx src ",
"test:vscode": "cross-env SKIP_PREFLIGHT_CHECK=true craco --inspect-brk test",
"test": "cross-env SKIP_PREFLIGHT_CHECK=true CI=true craco test --env=jest-environment-jsdom-sixteen --maxWorkers=4 --transformIgnorePatterns \"node_modules/(?!date-fns)/\"",
"test:watch": "cross-env SKIP_PREFLIGHT_CHECK=true CI=true craco test --env=jest-environment-jsdom-sixteen --maxWorkers=4 --transformIgnorePatterns \"node_modules/(?!date-fns)/\" --watch",
"test:debug": "cross-env SKIP_PREFLIGHT_CHECK=true CI=true craco test --inspect-brk test --runInBand --no-cache --env=jest-environment-jsdom-sixteen --maxWorkers=4 --transformIgnorePatterns \"node_modules/(?!date-fns)/\"",
"eject": "react-scripts eject",
"generate-sw": "sw-precache --root=build --config scripts/sw-precache-config.js && uglifyjs build/service-worker.js -o build/service-worker.js"
},
"reactSnap": {
"inlineCss": true,
"puppeteerArgs": [
"--no-sandbox",
"--disable-setuid-sandbox"
]
},
"cracoConfig": "./craco.config.js",
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"dependencies": {
"#apollo/client": "^3.3.4",
"#auth0/auth0-react": "^1.2.0",
"#date-io/date-fns": "1.3.13",
"#material-ui/core": "4.11.1",
"#material-ui/icons": "4.9.1",
"#material-ui/lab": "^4.0.0-alpha.55",
"#material-ui/pickers": "^3.2.10",
"#material-ui/system": "4.9.14",
"#nivo/calendar": "0.67.0",
"#nivo/core": "0.67.0",
"#nivo/line": "0.67.0",
"#reach/router": "^1.3.3",
"#testing-library/jest-dom": "^5.11.1",
"aws-appsync-auth-link": "^2.0.3",
"aws-sdk": "^2.714.0",
"clsx": "^1.1.1",
"components": "*",
"date-fns": "^2.14.0",
"exceljs": "^3.9.0",
"file-saver": "^2.0.2",
"formik": "^2.1.4",
"formik-persist": "^1.1.0",
"graphql": "^15.0.0",
"immer": "^6.0.9",
"linkifyjs": "^2.1.9",
"lodash": "^4.17.15",
"logrocket": "^1.0.7",
"material-table": "^1.59.0",
"msw": "^0.24.2",
"randomcolor": "^0.6.2",
"react": "17.0.1",
"react-apollo": "^3.1.5",
"react-dom": "17.0.1",
"react-elastic-carousel": "^0.6.4",
"react-error-boundary": "^2.2.1",
"react-loading-skeleton": "^2.1.1",
"react-prerendered-component": "^1.2.4",
"react-scripts": "4.0.1",
"source-map-explorer": "^2.4.2",
"styled-components": "^5.2.1",
"suneditor-react": "^2.13.1",
"tiny-slider-react": "^0.4.0",
"uuid": "^8.2.0",
"validate-password": "^1.0.4",
"xlsx": "^0.16.1",
"yup": "^0.29.1"
},
"devDependencies": {
"uglify-js": "3.12.8",
"#craco/craco": "6.1.1",
"#testing-library/dom": "^7.29.0",
"#testing-library/react": "^11.2.2",
"#testing-library/user-event": "^12.5.0",
"#types/auth0-js": "^9.13.1",
"#types/file-saver": "^2.0.1",
"#types/jest": "^26.0.16",
"#types/linkifyjs": "^2.1.3",
"#types/lodash": "^4.14.154",
"#types/node": "^14.0.6",
"#types/randomcolor": "^0.5.5",
"#types/reach__router": "^1.3.5",
"#types/react": "17.0.0",
"#types/react-dom": "17.0.0",
"#types/tiny-slider-react": "^0.3.2",
"#types/uuid": "^8.0.0",
"#types/yup": "^0.29.1",
"#typescript-eslint/eslint-plugin": "^4.9.0",
"#typescript-eslint/parser": "^4.9.0",
"cross-env": "^7.0.2",
"dynamic-cdn-webpack-plugin": "^5.0.0",
"eslint-config-airbnb-typescript": "^12.0.0",
"eslint-config-prettier": "^6.15.0",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-prettier": "^3.2.0",
"eslint-plugin-react": "^7.21.5",
"gulp": "^4.0.2",
"gulp-json-editor": "^2.5.4",
"gulp-replace": "^1.0.0",
"html-webpack-plugin": "^4.5.0",
"husky": "^4.3.0",
"jest-axe": "^3.4.0",
"jest-canvas-mock": "^2.3.0",
"jest-dom": "^4.0.0",
"jest-environment-jsdom-sixteen": "^1.0.3",
"lint-staged": "^10.5.2",
"prettier": "2.0.5",
"react-snap": "^1.23.0",
"sw-precache": "^5.2.1",
"typescript": "4.1.2",
"webpack-cdn-plugin": "^3.3.1"
},
"resolutions": {
"apollo-client": "2.6.4"
}
}
The /app/craco.config.js file:
const path = require('path');
/**
* Allows us to edit create-react-app configuration
* without ejecting.
*
*
*/
const { getLoader, loaderByName } = require('#craco/craco');
const absolutePath = path.join(__dirname, '../components');
const schonComponents = path.join(
__dirname,
'./node_modules/#schon/components',
);
module.exports = {
webpack: {
configure: (webpackConfig, { env, paths }) => {
// https://medium.com/frontend-digest/using-create-react-app-in-a-monorepo-a4e6f25be7aa
const { isFound, match } = getLoader(
webpackConfig,
loaderByName('babel-loader'),
);
if (isFound) {
const include = Array.isArray(match.loader.include)
? match.loader.include
: [match.loader.include];
match.loader.include = include.concat(absolutePath, schonComponents);
}
return {
...webpackConfig,
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(
/[\\/]node_modules[\\/](.*?)([\\/]|$)/,
)[1];
// npm package names are URL-safe, but some servers don't like # symbols
return `npm.${packageName.replace('#', '')}`;
},
},
},
},
},
};
},
},
};
And some of the vscode test debugging configs:
{
"version": "0.2.0",
"configurations": [
// {
// "name": "Debug CRA Tests App",
// "type": "node",
// "request": "launch",
// "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/yarn",
// "args": ["workspace app test:debug"],
// "env": {
// "SKIP_PREFLIGHT_CHECK": "true"
// },
// "cwd": "${workspaceRoot}",
// "protocol": "inspector",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen"
// },
{
"type": "node",
"name": "vscode-jest-tests",
"request": "launch",
"runtimeExecutable": "yarn",
"runtimeArgs": [
"workspace",
"app",
"test:vscode",
"--runInBand",
"--env=jest-environment-jsdom-sixteen",
"--transformIgnorePatterns \"node_modules/(?!date-fns)/\""
],
"args": [
// "--runInBand",
// "--fileDirname", // ADDING THE CURRENT FILENAME DIR FOR THE SCRIPT
// "${fileDirname}"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true
// "program": "${workspaceFolder}/tools/vscode-jest-tests/index.js" // THE SCRIPT
},
// {
// "name": "Debug CRA Tests",
// "type": "node",
// "request": "launch",
// "runtimeExecutable": "${workspaceRoot}/app/node_modules/.bin/craco",
// "runtimeArgs": [
// "test",
// "--config ${workspaceRoot}\\app\\craco.config.js",
// // "--runInBand",
// // "--no-cache",
// // "--env=jsdom",
// "--transformIgnorePatterns \"node_modules/(?!date-fns)/\"",
// "-t"
// ],
// "env": {
// "SKIP_PREFLIGHT_CHECK": "true"
// },
// "cwd": "${workspaceRoot}/app",
// "protocol": "inspector",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen"
// }
{
"name": "Debug CRA Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/app/node_modules/.bin/react-scripts",
"args": [
"test",
"--runInBand",
"--no-cache",
"--watchAll=false",
"--config=jest.config.js"
],
"env": {
"CI": "true",
"SKIP_PREFLIGHT_CHECK": "true"
},
"cwd": "${workspaceRoot}/app",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true
}
]
}

How to use third party web service in reactjs?

I am working on ReactJs in which i am trying to use third party api. As i tested the api in postman, all the api's are working fine. But when i integrated the api in my project i am getting CORS error.
I have searched on the google. I found the solution that use Proxy server. I tried using proxy server but still not working for me. May be I did not implement it correctly.
I referred these links :
https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/
https://levelup.gitconnected.com/overview-of-proxy-server-and-how-we-use-them-in-react-bf67c062b929
DO i need to install anything?
Any help is appreciated.
package.json
{
"name": "WebPortal",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --port 8081 --hot --host localhost",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#material-ui/core": "^4.9.0",
"#mdi/font": "^4.9.95",
"babel-loader": "^7.1.5",
"bootstrap": "^4.4.1",
"bootstrap4-toggle": "^3.6.1",
"jquery": "^3.4.1",
"pm2": "^4.2.3",
"popper.js": "^1.16.1",
"react": "^16.12.0",
"react-bootstrap-toggle": "^2.3.2",
"react-datetime-picker": "^2.9.0",
"react-dom": "^16.12.0",
"react-easy-crop": "^2.0.1",
"react-image-crop": "^8.5.0",
"react-loader-spinner": "^3.1.5",
"react-router-dom": "^5.1.2",
"react-toasts": "^3.0.6",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1"
},
"devDependencies": {
"#babel/core": "^7.4.3",
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#babel/preset-env": "^7.4.3",
"#babel/preset-react": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^8.0.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^3.4.2",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.1.3",
"webpack": "^4.30.0"
},
"proxy": "api.sysco.com"
}
temp.js
fetch('/token?grant_type=client_credentials', {method: 'POST'}).then(
data => {
console.log("data==========>", data);
},
error => {
console.log("error==========>", error);
}
);
If you want a way to do this for development purposes (as some apis don't allow adding localhost or http to allow origin) you can use cors disabled mode of the browsers like for chrome
google-chrome --disable-web-security does the trick OR in windows you can create a shortcut (rightclick > send to desktop ) and in its properties(right-click > properties) add the flag --disable-web-security after ***/chrome.exe (you will see a textbox).
If you want a solution for production, there is no other way than configuring the api for your website. You can follow the link provided by Dominic to learn more about cors. All the third pary API uses allow any origin header or atleast give a way to configure cors in console.

electron: Can't load http://localhost:8080

I can load http://localhost:8080 from chrome, but It occur error with win.loadURL('http://localhost:8080/');, and I don't know why.
Error code :
Failed to load resource:localhost:8080 net::ERR_EMPTY_RESPONSE,
My code
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function load() {
mainWindow.loadURL('http://127.0.0.1:8080');
}
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadURL('http://127.0.0.1:8080');
mainWindow.loadFile('index.html');
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
});
// In this file you can include the rest of your app's specific main process
And this is package.json
{
"version": "1.0.0",
"name": "idena-pocket",
"private": true,
"main": "public/main.js",
"scripts": {
"dev": "export NODE_ENV=development && webpack-dev-server --https --host 127.0.0.1 --open",
"electron-dev": "concurrently \"BROWSER=none npm run dev\" \"electron .\"",
"electron-dev1": "concurrently \"BROWSER=none\" \"electron .\"",
"electron-dev2": "concurrently \"BROWSER=none npm run dev\" \"wait-on https://10.0.2.2:8080/ && electron .\"",
"electron-package": "./node_modules/.bin/electron-builder -c.extraMetadata.main=build/start-electron.js",
"preelectron-package": "npm run build",
"i18-scanner": "i18next-scanner src/**/*.{js,jsx,ts,tsx,html}",
"format": "prettier-standard --format"
},
"dependencies": {
"react-scripts": "0.8.5",
"bip39": "^3.0.2",
"concurrently": "^6.0.2",
"connected-react-router": "^6.8.0",
"crypto-js": "^4.0.0",
"electron": "^12.0.6",
"electron-builder": "^22.11.1",
"electron-is-dev": "^2.0.0",
"history": "^4.10.1",
"i18next": "^19.4.4",
"i18next-browser-languagedetector": "^4.1.1",
"i18next-scanner": "^2.11.0",
"idena-js": "1.1.5",
"react": "^16.13.1",
"react-copy-to-clipboard": "^5.0.2",
"react-dom": "^16.13.1",
"react-hook-form": "^5.5.3",
"react-i18next": "^11.4.0",
"react-redux": "^7.2.0",
"react-router-dom": "^5.1.2",
"react-tooltip": "^4.2.5",
"redux": "^4.0.5",
"styled-components": "^5.0.1",
"sweetalert": "^2.1.2",
"wait-on": "^5.3.0"
},
"devDependencies": {
"#types/react": "^16.9.25",
"#types/react-dom": "^16.9.5",
"#types/react-redux": "^7.1.7",
"#types/react-router-dom": "^5.1.3",
"#types/styled-components": "^5.1.0",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.1.1",
"css-loader": "^3.4.2",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^3.2.0",
"pre-commit": "^1.2.2",
"prettier-standard": "^16.3.0",
"react-hot-loader": "^4.12.20",
"ts-loader": "^6.2.1",
"typescript": "^3.8.3",
"url-loader": "^4.1.0",
"webpack": "^4.43.0",
"webpack-bundle-analyzer": "^3.7.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0",
"workbox-webpack-plugin": "^5.1.3"
},
"pre-commit": [
"format"
]
}

Resources