SyntaxError: Unexpected token T in JSON at position 0 - json

I'm coding a Typescript application. In This application I'ld read some json file with the function d3.json, but the code doesn't work. The error is this:
SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse ()
at Object. (d3-request.node.js:176)
at respond (d3-request.node.js:39)
at exports.XMLHttpRequest.onload.xhr.onreadystatechange (d3-request.node.js:30)
at exports.XMLHttpRequest.dispatchEvent (XMLHttpRequest.js:591)
at setState (XMLHttpRequest.js:610)
at exports.XMLHttpRequest.handleError (XMLHttpRequest.js:532)
at module.exports.errorHandler (XMLHttpRequest.js:459)
at module.exports.EventEmitter.emit (events.js:81)
at request.js:142
The code is this:
export async function setSelectConfiguration(
filenameJson: string, storeData: (str: string) => void, element: JQuery,
listenerFunction:(e: JQueryEventObject) => void) {
await d3.json("filename2.json", function(error, data) {
if(error) {
console.log(error);
} else {
console.log(data);
storeData(data.toString())
}
});
element.on("change", listenerFunction);
}
The json is this:
{
"files": [
{
"name": "time_sensitive_test.json",
"type": "user",
"owner": "Master",
"data_type": "linear data",
"description": "Utenti master (Enrica) periodo 20/05/2014-16/10/2014",
"ids_description": "accesso risorse",
"ods_description": "chat/forum",
"bds_description": "login/logout"
}
]}
the gulpfile.js:
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
pages: ['src/*.html']
};
gulp.task('copyHtml', function () {
return gulp.src(paths.pages)
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['copyHtml'], function () {
return browserify({
basedir: '.',
debug: true,
entries: ['src/main.ts'],
cache: {},
packageCache: {}
})
.plugin(tsify)
.transform('babelify', {
presets: ['env','stage-0'],
extensions: ['.ts'],
plugins: ['transform-runtime','transform-async-to-generator']
})
.bundle()
.pipe(source('project.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
the package.json:
{
"name": "project",
"version": "1.0.0",
"description": " Project",
"main": "./dist/project.js",
"directories": {
"example": "example"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": " ... "
},
"author": " ",
"license": "ISC",
"bugs": {
"url": "... "
},
"homepage": "...",
"devDependencies": {
"#types/d3": "^4.10.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-0": "^6.24.1",
"babelify": "^8.0.0",
"browserify": "^14.5.0",
"gulp": "^3.9.1",
"gulp-sourcemaps": "^2.6.3",
"gulp-typescript": "^3.2.3",
"gulp-uglify": "^3.0.0",
"gulp-util": "^3.0.8",
"tsify": "^3.0.4",
"typescript": "^2.6.2",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"watchify": "^3.9.0"
},
"dependencies": {
"#types/node": "^8.5.7",
"babel-polyfill": "^6.26.0",
"babel-runtime": "^6.26.0",
"d3": "^4.12.2",
"webpack": "^3.10.0"
}
}
the tsconfig.json:
{
"files": [
...
],
"compilerOptions": {
"module": "commonjs",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"noImplicitAny": true,
"target": "es2015",
"lib": ["es2015", "es2016", "dom", "es2017", "es6", "es5"],
"experimentalAsyncFunctions": true,
"typeRoots": [
"./node_modules/#types"
]
},
"exclude": [
"node_modules",
"dist"
]
}
the webpack.config.json:
module.exports = {
context: __dirname + '/src',
entry: ['babel-polyfill', './main.ts'],
output: {
path: 'dist',
filename: 'project.js'
},
module: {
loaders: [
{
test: /\.js/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
}
};
I ran the code compiled outside the IDE, but the error appeared equally; so it should not be some strange fault of the IDE.
I've tried to read the file with in a pure javascript app and all works fine; so the problem is not to be found in the files.
What could be the problem? for example: does it need any special modules or configurations?

Related

ParseError: 'import' and 'export' may appear only with 'sourceType: module' - swiper.esm.js

I've a problem with gulp and browserify. I want minify my index.js but he's import a figure.js with import 'swiper'. And Swiper contains "import" and "export" too.
My package.json
{
"name": "gulp-frontend-kit",
"version": "2.0.0",
"description": "Gulp boilerplate front-end dev Archriss",
"author": "Archriss",
"dependencies": {
"cookies-js": "^1.2.3",
"custom-event-polyfill": "^1.0.7",
"element-qsa-scope": "^1.0.1",
"html-truncate": "^1.2.2",
"lightgallery.js": "^1.0.1",
"node-fetch": "^3.2.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"swiper": "^8.2.2",
"tingle.js": "^0.16.0",
"tippy.js": "^6.3.7"
},
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.5",
"#babel/plugin-proposal-class-properties": "^7.17.12",
"#babel/plugin-transform-runtime": "^7.18.5",
"#babel/preset-env": "^7.18.2",
"#babel/preset-react": "^7.17.12",
"#babel/register": "^7.15.3",
"autoprefixer": "^10.4.7",
"babel-eslint": "^10.1.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babelify": "^10.0.0",
"browserify": "^17.0.0",
"css-mqpacker": "^7.0.0",
"cssnano": "^5.1.11",
"del": "^6.1.1",
"eslint": "^8.17.0",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-standard": "^5.0.0",
"gulp": "^4.0.0",
"gulp-buffer": "0.0.2",
"gulp-clean-css": "^4.3.0",
"gulp-combine-mq": "^0.4.0",
"gulp-concat": "^2.6.0",
"gulp-imagemin": "^7.1.0",
"gulp-livereload": "^4.0.2",
"gulp-postcss": "^9.0.1",
"gulp-sass": "^5.1.0",
"gulp-sourcemaps": "^3.0.0",
"gulp-stylelint": "^13.0.0",
"gulp-terser": "^2.1.0",
"gulp-uglify": "^3.0.2",
"gutil": "^1.6.4",
"imagemin-pngquant": "^9.0.2",
"node-sass": "^7.0.1",
"postcss-markdown": "^1.2.0",
"sass": "^1.52.3",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^2.0.0"
},
"scripts": {
"start": "gulp",
"watch": "gulp watch",
"build": "gulp build"
},
"browserify": {
"transform": [
[
"babelify",
{
"presets": [
"#babel/preset-env"
]
}
]
]
}
}
My .babelrc
{
"presets": [
"#babel/react" ,
"#babel/env" ,
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
My gulpfile.babel.js
const {src, dest, watch, series, parallel} = require('gulp'),
browserify = require('browserify'),
buffer = require('vinyl-buffer'),
concat = require('gulp-concat'),
livereload = require('gulp-livereload'),
source = require('vinyl-source-stream'),
sourcemaps = require('gulp-sourcemaps'),
uglify = require('gulp-uglify'),
babelify = require("babelify")
const FILENAMES = {jsCode: 'app.js', jsVendor: 'vendor.js'};
const PATHS = {
dest: {
global: './dist',
imgFolder: 'img',
prodFolder: 'prod',
devFolder: 'dev'
},
src: {
assets: ['src/assets/**', '!src/assets/{img,img/**}'],
html: 'src/html/*.html',
img: 'src/assets/img/**/*',
jsCode: ['src/js/**/*.js', '!src/js/{vendor,vendor/**}'],
jsEntry: 'src/js/index.js',
jsVendor: 'src/js/vendor/*.js',
scss: 'src/scss/**/*.scss'
}
};
function html() {
return src(PATHS.src.html).pipe(livereload());
}
function JSVendor(isDev) {
const targetFolder = isDev === true ? PATHS.dest.devFolder : PATHS.dest.prodFolder;
return src(PATHS.src.jsVendor)
.pipe(concat(FILENAMES.jsVendor))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(dest(PATHS.dest.global + '/' + targetFolder))
.pipe(livereload());
}
function JSCode(isDev) {
const targetFolder = isDev === true ? PATHS.dest.devFolder : PATHS.dest.prodFolder;
return (
browserify({
entries: [PATHS.src.jsEntry],
// Pass babelify as a transform and set its preset to #babel/preset-env
transform: [babelify.configure({presets: ["#babel/preset-env"]})]
})
// Bundle it all up!
.bundle()
// Source the bundle
.pipe(source("bundle.js"))
// Then write the resulting files to a folder
.pipe(dest(PATHS.dest.global + '/' + PATHS.dest.devFolder))
);
}
function catchJSErrors(err) {
if (err instanceof SyntaxError) {
console.log('Syntax Error');
console.log(err.message);
console.log(err.codeFrame);
} else {
console.log('Error', err.message);
}
this.emit('end');
}
exports.dev = function () {
const isDev = true;
watch(PATHS.src.html, html);
watch(PATHS.src.jsVendor, JSVendor(isDev));
watch(PATHS.src.jsCode, JSCode(isDev));
};
exports.build = function () {
const devOptions = {type: 'changed'};
};
exports.default = series(html);
And My error
$ gulp dev
[17:58:49] Requiring external module #babel/register
[17:58:50] Using gulpfile E:\docker\images\XXX\web\themes\custom\XXX\front\gulpfile.babel.js
[17:58:50] Starting 'dev'...
[17:58:51] 'dev' errored after 1.13 s
[17:58:51] Error:
E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\swiper\swiper.esm.js:13
export { default as Swiper, default } from './core/core.js';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
at formatError (C:\Users\XXX\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\format-error.js:21:10)
at Gulp.<anonymous> (C:\Users\XXX\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\log\events.js:33:15)
at Gulp.emit (node:events:539:35)
at Gulp.emit (node:domain:475:12)
at Object.error (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\undertaker\lib\helpers\createExtensions.js:61:10)
at handler (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\now-and-later\lib\map.js:50:14)
at f (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\once\once.js:25:25)
at f (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\once\once.js:25:25)
at tryCatch (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\async-done\index.js:24:15)
at done (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\async-done\index.js:40:12)
My versions :
npm -v : 8.12.1
node -v : v16.15.1
gulp -v : CLI : 2.3.0 - Local : 4.0.2
How fix this error ?
Try to add global: true
transform: [babelify.configure({global: true, presets: ["#babel/preset-env"]})]

Webpack images path in build

webpack break my image paths
This is my code
and it is error
Refused to apply style from 'http://localhost:8080/style.css' because
its MIME type ('text/html') is not a supported stylesheet MIME type,
and strict MIME checking is enabled.
webpack.config.js
i use file-loader but this not help me
const path = require('path');
const HtmlWebpackPlugin = require('*html-webpack-plugin*');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devServer = (isDev) => !isDev ? {} : {
devServer: {
open: true,
port: 8080,
static: {
watch: true,
directory: '**/*.html',
},
},
};
module.exports = ({development}) => ({
mode: development ? 'development' : 'production',
devtool: development ? 'inline-source-map' : false,
entry: {
app:'./src/index.js',
main: './src/shelter/pages/main/index.js',
pets: './src/shelter/pages/pets/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
assetModuleFilename: 'assets/images/[hash][ext]',
},
module: {
rules: [
{
test: /\.(?:ico|gif|png|jpg|jpeg|svg|html|text)$/i,
use: ['file-loader']
},
{
test: /\.(woff(2)?|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
},
{
loader: 'file-loader',
options: {
publicPath: '/../../image',
name: `assets/images/[hash].[ext]`,
}
},
]
},
resolve: {
extensions: ['.ts', '.js']
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }),
new HtmlWebpackPlugin({ template: './src/shelter/pages/main/index.html' }),
],
...devServer(development)
});
package.json
it is my package.json
{
"name": "webpack",
"scripts": {
"build": "webpack",
"dev": "webpack server --env development"
},
"devDependencies": {
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.6.0",
"sass": "^1.50.0",
"sass-loader": "^12.6.0",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2"
},
"dependencies": {
"file-loader": "^6.2.0",
"resolve-url-loader": "^5.0.0",
"webpack-dev-server": "^4.8.1"
}
}
My structure fails enter image description here

Webpack, babelrc dynamic import not working

I spent quite some time trying to figure this out myself but here I am, with no more options to consider than to reach out to the community for some guidance.
I am trying to do something very simple in principle, dynamically import a component with WebPack, using ES6 modules and babelrc.
I have the following app architecture:
-root
-- root/.webpack.dev.js
-- root/.webpack.prod.js
-- root/.babelrc
-- root/package.json
-- root/node_modules/
-- root/dist/
-- root/src/
--- root/src/index.js
--- root/src/modules/
--- root/src/modules/module1.js
--- root/src/modules/module2.js
--- root/src/modules/module3.js
--- root/src/modules/module4.js
--- root/src/modules/module5.js
In my module1.js (not the real name) I am using the following code to dynamically import module2.js:
async function load(configObject) {
const {
init,
requestPermissions
} = await import( /* webpackChunkName: "chunkname" */ `./module2.js`)
init(configObject)
_namespace.requestPermissions = requestPermissions;
}
My .babelrc file:
{
"presets": [
["#babel/preset-env", {
"targets": "> 0.25%, not dead"
}]
],
"plugins": ["#babel/plugin-syntax-dynamic-import",
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
],
"comments": true
}
// "#babel/preset-env"
My Webpack config:
const path = require('path');
const webpack = require('webpack')
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin
const WorkboxPlugin = require('workbox-webpack-plugin');
const {
InjectManifest
} = require('workbox-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: {
lib: "./src/index.js"
},
mode: 'development',
module: {
rules: [{
test: /\.js$/,
use: [{
loader: "babel-loader"
}],
exclude: /node_modules/
}]
},
optimization: {
minimizer: [new TerserPlugin({
test: /\.js(\?.*)?$/i,
parallel: true,
cache: true,
terserOptions: {
ecma: 8,
warnings: false,
parse: {
ecma: 8,
},
compress: {
warnings: false,
comparisons: false,
},
mangle: {
safari10: true,
},
module: false,
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
toplevel: false,
nameCache: null,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
safari10: false,
},
})],
},
output: {
filename: '[name].js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: "/"
},
devServer: {
contentBase: "dist",
compress: true,
stats: {
colors: true
},
overlay: true
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'API_URL': JSON.stringify('ENDPOINT')
}
}),
new BundleAnalyzerPlugin({
generateStatsFile: true
}),
new WorkboxPlugin.GenerateSW({
"swDest": "firebase-messaging-sw.js",
}),
new InjectManifest({
"swSrc": path.join('src', 'firebase-messaging-sw.js')
})
]
};
My package.json:
{
"name": "refactor",
"version": "1.0.0",
"description": "",
"main": "backuprefacto.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "NODE_ENV=production webpack --config=webpack.prod.js",
"build:dev": "webpack --config=webpack.dev.js",
"start": "webpack-dev-server --config=webpack.dev.js"
},
"keywords": [],
"private": true,
"license": "ISC",
"devDependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.5.5",
"babel-loader": "^8.0.6",
"babel-minify": "^0.5.1",
"babel-minify-webpack-plugin": "^0.3.1",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"terser-webpack-plugin": "^1.4.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.39.2",
"webpack-bundle-analyzer": "^3.4.1",
"webpack-cli": "^3.3.7",
"webpack-dev-server": "^3.8.0",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"#babel/core": "^7.5.5",
"#babel/plugin-transform-runtime": "^7.5.5",
"#babel/runtime": "^7.5.5",
"firebase": "^6.4.0",
"save": "^2.4.0"
}
}
I have checked all my modules, none of them expect for module1.js are calling module2.js.
I have also explored the option of webpack comments being deleted by babel and therefore added a comments: true to make sure the webpackChunkName is not being deleted but in the end, the only thing that gets built is my lib.js, not the lib.bundle.js that I expect.
I have also tried to remove all the TerserPlugin bit to check if that could have the same impact but nothing changed there.
In the need, what I am looking for is simply to have the module2.js loaded whenever it is invoked, and I therefore expect a new network request to materialise this.
Well, it turns out that if you want to use dynamic imports you need to make sure first that you are not importing at all the module at the top....
In module1.js I was importing twice, once at the top, the "regular way", once the dynamic way which was obviously leading to module2.js being consistently loaded.
I resolve my problem by modify .babelrc, modules: false
["#babel/preset-env", {
"loose": true,
"useBuiltIns": "usage",
"corejs": 3,
"modules": false
}],

How can we get data from mysql database in angular 7 application by using node.js and display it on angular component html page

I have tried every thing but i cant under stand how to reach my goal.
Now my main goal is that i want to get data from mysql database and then access this information in angular component which is page-one.component.ts file. Now i can connect to the database and can get the data from database in server.js file. but i cant understand how to get the information in angular component. The method i have tried so far is that i include the server.js file in angular.json file and then include the function "get_data" (get_data function fetch data from database in server.js file) in my page-one.component.ts file and then i call the function in page-one.component.ts file. The function is called, but the problem is that i got error in server.js file that " Cannot read property 'createConnection' of undefined". This error stops me from getting the information from database. but when i call this get_data function in server.js file i got the database information and i can print the information in console.
Can any one give me the solution please.
I think the error is because of the context of variable.
but please guide me.
My server.js file code.
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
var mysql = require('mysql');
var dbconfig = {
host: "localhost",
user: "root",
password: "",
database: "mydb"
}
var con = mysql.createConnection(dbconfig);
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
get_data();
function get_data(){
console.log("function called");
var con = this.mysql.createConnection(dbconfig); ===> GOT ERROR HERE
con.query("SELECT * FROM teacher", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
server.listen(port, () => {
console.log(`server running on port ${port} `);
})
My page-one.component.ts file code.
import { Component, OnInit } from '#angular/core';
import { Http } from '#angular/http';
declare function get_data(): any;
#Component({
selector: 'app-page-one',
templateUrl: './page-one.component.html',
styleUrls: ['./page-one.component.css']
})
export class PageOneComponent implements OnInit {
constructor(private http: Http) { }
ngOnInit() {
get_data();
}
}
My angular.json file code.
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"myapp": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/myapp",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts":
[
"server.js" ===> INCULDED THE SERVER.JS FILe HERE
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "myapp:build"
},
"configurations": {
"production": {
"browserTarget": "myapp:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "myapp:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"myapp-e2e": {
"root": "e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "myapp:serve"
},
"configurations": {
"production": {
"devServerTarget": "myapp:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "myapp"
}
" Cannot read property 'createConnection' of undefined"
const mysql = require('mysql2');
const connection = mysql.createPool({
host: 'localhost',
user: '',
password: '',
database: '',
connectionLimit: 10,
queueLimit: 0
});
connection.promise((err) => {
if (err) throw err;
console.log('connected!');
});
module.exports = connection.promise();
app.get("/youroute", (req, res, next) => {
"use strict";
const getProduct = "SELECT * FROM yourtable";
database.query(getProduct, (err, rows, fields) => {
if (err) {
res.status(500).send({ error: 'Something failed!' })
};
res.status(200).json({
message: "",
product: rows,
});
});
});
Service for Angular
export interface You {
id: number,
title: string,
content: string
}
Get Method on Model Angular
getData() {
this.http.get<{message:string,name:Name[]}>("URL")
.subscribe(result =>{
console.log(result);
});
and in HTML make For Loop with NGFOR for display your data

ERROR when trying to run karma test

I am having problems to setup karma with Angular 5.2.0 (without Cli)
The Angular application is working, but the problem is with karma, when I try to run the test i get this ERROR:
karma start
Hash: ccc4545dd1d9416a823b
Version: webpack 3.10.0
Time: 58ms
webpack: Compiled successfully.
13 01 2018 15:34:59.123:WARN [karma]: No captured browser, open http://localhost:9876/
13 01 2018 15:34:59.134:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
13 01 2018 15:34:59.136:INFO [launcher]: Launching browser Chrome with unlimited concurrency
13 01 2018 15:34:59.147:INFO [launcher]: Starting browser Chrome
13 01 2018 15:35:00.726:INFO [Chrome 63.0.3239 (Windows 10 0.0.0)]: Connected on socket 37NRWsbdgw5x2CTBAAAA with id 42149942
Chrome 63.0.3239 (Windows 10 0.0.0) ERROR
{
"message": "Uncaught SyntaxError: Unexpected token {\nat src/app/app.component.spec.ts:2:8\n\nSyntaxError: Unexpected token {",
"str": "Uncaught SyntaxError: Unexpected token {\nat src/app/app.component.spec.ts:2:8\n\nSyntaxError: Unexpected token {"
}
First I got that ERROR with video/mp2t so I added the MIME fix. And now I got the above ERROR. It seems that karma is not resolving the TS or something, because I have tested the .spec.ts file with just one import and still get the same error.
app.component.spec.ts
import { TestBed, async } from '#angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should display the header text "Welcome to Momentz4Ever"', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to Momentz4Ever');
}));
});
tsconfig.ts
{
"compileOnSave": false,
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"baseUrl": "src",
"outDir": "./dist",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2016",
"dom"
],
"types": [
"node",
"jasmine"
]
},
"awesomeTypeScriptLoaderOptions": {
"useWebpackText": true
}
}
webpack.config.ts
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ContextReplacementPlugin } = require('webpack');
module.exports = {
entry: {
main: './src/index.ts'
},
output: {
path: path.join(__dirname, "../dist/"),
filename: "[name].bundle.js",
},
resolve: {
extensions: ['.js', '.ts', '.html']
},
devServer: {
contentBase: path.join(__dirname, "../dist/"),
port: 9000
},
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /.ts$/, use: ['awesome-typescript-loader', 'angular2-template-loader'] },
{ test: /.html$/, use: 'raw-loader' }
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html",
showErrors: true,
title: "Webpack App",
path: path.join(__dirname, "../dist/"),
hash: true
}),
new ContextReplacementPlugin(
/\#angular(\\|\/)core(\\|\/)esm5/,
path.resolve(__dirname, 'src')
)
]
}
karma.conf.ts
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: './src/app/app.component.spec.ts' }
],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-webpack'),
require('karma-sourcemap-loader'),
],
preprocessors: {
'./src/test.ts': ['webpack', 'sourcemap']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
package.json
{
"name": "",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "karma start",
"build": "webpack-dev-server --config webpack.config.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"#angular/common": "^5.2.0",
"#angular/compiler": "^5.2.0",
"#angular/core": "^5.2.0",
"#angular/forms": "^5.2.0",
"#angular/http": "^5.2.0",
"#angular/platform-browser": "^5.2.0",
"#angular/platform-browser-dynamic": "^5.2.0",
"#angular/router": "^5.2.0",
"core-js": "^2.5.3",
"rxjs": "^5.5.6",
"zone.js": "^0.8.20"
},
"devDependencies": {
"#types/jasmine": "^2.8.4",
"#types/node": "^9.3.0",
"angular2-template-loader": "^0.6.2",
"awesome-typescript-loader": "^3.4.1",
"css-loader": "^0.28.8",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.6",
"html-webpack-plugin": "^2.30.1",
"jasmine": "^2.8.0",
"jasmine-core": "^2.8.0",
"karma": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.1.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-typescript": "^3.0.9",
"karma-webpack": "^2.0.9",
"node-sass": "^4.7.2",
"raw-loader": "^0.5.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.1",
"ts-loader": "^3.2.0",
"tslint": "^5.9.1",
"typescript": "^2.6.2",
"url-loader": "^0.6.2",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.10.1"
}
}