I understand that is was a frequently asked question. I looked at many other topics on stack overflow about it and I still don't know what the issue is? Some are saying it's because it's reading the file type as a text/html MIME type however I declared in my index.html it as text/css and it's still throwing me an error in the console.
And when i change it to text/html in my index file, the error in the console goes away but my styles won't load at all on my page even though the path is correct?
Error i get in console: localhost/:1 Refused to apply style from 'http://localhost:1234/assets/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I've been stuck trying to figure this out for past 2 hours I think it's something small I'm missing.
Here is my project structure:
INDEX.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../assets/css/styles.css">
<title>Portfolio Application</title>
</head>
<body>
<div id="app"></div>
<!-- Bootstrap JS Library -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" type="text/javascript" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" type="text/javascript" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript" src="bundle.js"></script></body>
</html>
Webpack.config file
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: __dirname + "/src/index.js",
output: {
path: __dirname + "/public",
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['env', 'react', 'stage-0']
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
]
}
Server file (Main.js)
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const app = express();
const port = 8010;
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(cors());
app.use(function(req, res, next){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
app.use('/', express.static(__dirname + "/../public"));
app.listen(port, () => {
console.log(`app is listening in on port ${port}`);
});
Folder structure:
root
public (folder)
assets
fonts
images
bundle.js
index.html
server (folder)
main.js
src (folder)
common (folder)
components (folder)
index.js
routes.js
package.json
webpack.config.js
Related
Hi i Have a problem with MathJax library. I want to display the mathjax formula on the screen, but when I use window.MathJax I get the error that it is undefined. Here is how I installed the MathJax in my html file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<link rel="icon" href="/icons/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="/icons/favicon.ico" type="image/x-icon">
<!-- inject:css -->
<!-- endinject -->
<script type="text/x-mathjax-config">
MathJax = {
options: {
renderActions: {
addMenu: []
}
},
};
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<script async type="text/javascript" src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-svg.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>
<body>
<div id="application-content">
</div>
</body>
<!-- inject:js -->
<!-- endinject -->
<script type="application/javascript">
EMBED.default.init();
</script>
</html>
And here is the component where I use the library:
import React, { Component } from 'react';
export default class MathBlock extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
render() {
const text = this.props.block.getText();
const latexRegex = /\${2}(.*?)\${2}/;
const hasLatex = latexRegex.test(this.props.block.getText());
return (
<div>
<div
dangerouslySetInnerHTML={{
__html: hasLatex
? window.MathJax.tex2svg(text.replaceAll('$', '')).innerHTML
: window.MathJax.mathml2svg(text).innerHTML,
}}
/>
</div>
);
}
}
MathBlock.propTypes = {
block: React.PropTypes.object.isRequired,
};
Does anyone know what is the problem here?
Because the script tag that loads MathJax has the async attribute, it may not be loaded when your EMBED.default.init(); command likely will run before MathJax is loaded, and so before window.MathJax has been defined.
You could either remove the async attribute (which will mean your page will have to wait for MathJax to load and compile before the rest of the page is processed, slowing down your initial view of the page), or you could put the EMBED.default.init(); in MathJax's startup ready() function so that it is not performed until MathJax is loaded.
You are loading MathJax version 3, but your current configuration seems to be a mix of v2 and v3 configurations, and it is currently being ignored entirely by MathJax.
You could use
<script>
MathJax = {
options: {
renderActions: {
addMenu: []
}
},
tex: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
},
startup: {
ready() {
MathJax.startup.defaultReady();
EMBED.default.init();
}
}
};
</script>
(a correct v3 configuration) in place of your current configuration script, and see if that avoids the problem.
I am trying to generate an iron-ajax request and run a test on its response in Polymer 2.x with using the Mocha test suite.
However, when running this test I get the following error:
Cannot read property 'generateRequest' of undefined Context. at my-test.html:25
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>shop-catalogs</title>
<script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="/bower_components/web-component-tester/browser.js"></script>
<script src="/bower_components/web-component-tester/data/a11ySuite.js"></script>
<!-- Import the element(s) to test -->
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<script src="/bower_components/mocha/mocha.js"></script>
</head>
<body>
<test-fixture id="ajax">
<template>
<iron-ajax
handle-as="json"
headers$='{"Authorization": "Bearer api_access_token"}'
method="get"
url="https://api.com/test/endpoint">
</iron-ajax>
</template>
</test-fixture>
<script>
suite('shop-catalogs tests', () => {
var ajax;
test('checking for AJAX response', () => {
let request = ajax.generateRequest();
request.completes.then(response => {
console.log(response);
})
});
});
</script>
</body>
</html>
How can I make an AJAX request and handle the response in this framework?
I would advice to use fetch for this. It also will send an ajax call and is native to your browser.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>shop-catalogs</title>
<script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="/bower_components/web-component-tester/browser.js"></script>
<script src="/bower_components/web-component-tester/data/a11ySuite.js"></script>
<!-- Import the element(s) to test -->
<script src="/bower_components/mocha/mocha.js"></script>
</head>
<body>
<script>
suite('shop-catalogs tests', () => {
test('checking for AJAX response', (done) => {
fetch("https://api.com/test/endpoint", {
headers: {"Authorization": "Bearer api_access_token"}
}).then(res => {
assert.equal(res.status, 200)
return res.json()
})
.finally(res=>{
console.log(res)
done()//async test needs to tell when done
})
});
});
</script>
</body>
</html>
I want to scrape a HTML page in my nodejs application and form a list of head tags. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<script src="script.src"></script>
</head>
<body>
...
</body>
</html>
Desired Output:
['<meta charset="UTF-8">','<meta name="viewport" content="width=device-width, initial-scale=1.0">','<title>Document</title>', ...etc]
But I am a little stuck as the meta tags do not "close" so it needs more than simple regex and split. I wanted to use DOMParser but I am in the node environment. I tried to the xmldom npm package but it just returned a list of new line characters (\r\n).
One option is to use Cheerio to parse the HTML and extract the information you need from each element:
const cheerio = require('cheerio');
const htmlStr = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<script src="script.src"></script>
</head>
<body>
...
</body>
</html>`;
const $ = cheerio.load(htmlStr);
const headTags = [];
$('head > *').each((_, elm) => {
headTags.push({ name: elm.name, attribs: elm.attribs, text: $(elm).text() });
});
console.log(headTags);
Output:
[ { name: 'meta', attribs: { charset: 'UTF-8' }, text: '' },
{ name: 'meta',
attribs:
{ name: 'viewport',
content: 'width=device-width, initial-scale=1.0' },
text: '' },
{ name: 'title', attribs: {}, text: 'Document' },
{ name: 'link',
attribs: { rel: 'stylesheet', href: 'style.css' },
text: '' },
{ name: 'link',
attribs:
{ rel: 'shortcut icon',
href: 'favicon.ico',
type: 'image/x-icon' },
text: '' },
{ name: 'script', attribs: { src: 'script.src' }, text: '' } ]
use request npm to request your page and then after you get response , use cheerio npm to parse and get whatever you want from raw data .
Note : cheerio has syntax like jQuery
var request = require('request');
var cheerio = require('cheerio')
app.get('/scrape',(req,res)=>{
request('---your website url to scrape here ---', function (error, response, body) {
var $ = cheerio.load(body.toString())
let headContents=$('head').children().toString();
console.log('headContents',headContents)
});
});
I am relatively new to Angularjs, and am building a website. When I try to inject todo.html into the body tags of index.html nothing happens. I am not getting any errors in the console. I have read many of the similar posts to mine, and have already tried
Remove the ng-include from the body of index.html
Moved the links for angualrjs and bootstrap from the body of index.html to the head
Originally I used Ng-route but it did not work, so I implemented ui-router
I have tried both ng-route and ui-router,and both run without any errors. I don't think it has anything to do with either.
index.html
<html ng-app="todoApp">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Todo App</title>
<!-- Angular ans JS links-->
<script src="vendor/angular/angular.min.js"></script>
<script src="vendor/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="app/app.js"></script>
<script src="app/services/todo.service.js"></script>
<script src="app/controllers/todo.controller.js"></script>
<!-- <script src="vendor/angular-route/angular-route.min.js"></script>-->
<!--Jquery and Bootstrap Links-->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js" integrity="sha384-VjEeINv9OSwtWFLAtmc4JCtEJXXBub00gtSnszmspDLCtC0I4z4nqz7rEFbIZLLU"
crossorigin="anonymous"></script>
<!-- css links -->
<link href="vendor/bootstrap-css-only/css/bootstrap.min.css" rel="stylesheet"><!-- load bootstrap -->
<link rel="stylesheet" href="assets/css/todoApp.css">
<link rel="stylesheet" type="text/css" href="assets/css/Header-Picture.css">
</head>
<body >
<div ng-include="'app/views/header.html'"></div>
<!--<div ng-include="'app/views/footer.view.html'"></div>
-->
<ui-view></ui-view>
<!--<div ui-view></div>-->
</body>
</html>
App.js
var todoApp = angular.module('todoApp', [
'ui.router'
]);
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'views/todo.html',
controller: 'TodoController'
})});
todo.controller.js
todoApp.controller('TodoController', ['$scope', 'Todos', function TodoController($scope, Todos) {
$scope.formData = {};
console.log("in the TodoController");
// when landing on the page, get all todos and show them
Todos.get()
.success(function(data) {
$scope.todos = data;
});
// when submitting the add form, send the text to the spring API
$scope.createTodo = function() {
if(!$scope.todoForm.$valid) {
return;
}
Todos.create($scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos.push(data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
Todos.delete(id)
.success(function(data) {
angular.forEach($scope.todos, function(todo, index){
if(todo.id == id) {
$scope.todos.splice(index, 1);
}
});
});
};
// when submitting the add form, send the text to the node API
$scope.saveTodo = function(todo) {
Todos.update(todo)
.success(function(data) {
$scope.editedTodo = {};
});
};
$scope.editedTodo = {};
$scope.editTodo = function(todo) {
$scope.editedTodo = todo;
}
$scope.revertTodo = function() {
$scope.editedTodo = {};
}
}]);
You should be using otherwise to force the first state to be loaded as below
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'todo.html',
})
$urlRouterProvider.otherwise('/');
});
Your index.html will look like
<div ng-include="'app/views/header.html'"></div>
<ui-view>
</ui-view>
LIVE DEMO
I added the code posted by #Aravind to my project which I belive was an improvement on my own and was correct. But the issue was the file path to the todo.html. The file path in the original was views/todo.html
the correct path is app/views/todo.html
My original code:
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'views/todo.html',
controller: 'TodoController'
})});
Current Working Code
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'app/views/todo.html',
})
$urlRouterProvider.otherwise('/');
});
I'm completely brand new to React JS and am trying to create an application that will grab JSON data from a pokemon API, which I will then use to display on screen. Right now, I have it set up so that the user has to input the name of the pokemon they are looking for, i.e. pikachu, and when the search button is pressed, the application will make the API call to return the JSON. I've been searching for the past few days, and cannot seem to find anything to work with the way I currently have my code set up. How do I bind the JSON output to a component that I would then be able to display to the user?
Here's the js code (App.js)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Text field value is: ' + this.state.value);
fetch('https://pokeapi.co/api/v2/pokemon/'+this.state.value+'/')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data.name +" "+ data.id);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<input type="text"
placeholder="enter name of pokemon here"
value={this.state.value}
onChange={this.handleChange}
/>
<button type="button" onClick={this.handleSubmit}>Search the Pokedex</button>
</div>
);
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
Screenshot of issue:
http://imgur.com/a/g9H5r
Try this
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
data: {} //filled by fetch data from API
};
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Text field value is: ' + this.state.value);
var _this = this;
fetch('https://pokeapi.co/api/v2/pokemon/'+this.state.value+'/')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data.name +" "+ data.id);
_this.setState({data: data});
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
_this.setState({data: {}});
});
}
render() {
var data = this.state.data;
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<input type="text"
placeholder="enter name of pokemon here"
value={this.state.value}
onChange={this.handleChange.bind(this)}
/>
<button type="button" onClick={this.handleSubmit.bind(this)}>Search the Pokedex</button>
<h3>{data.id}</h3>
<h3>{data.name}</h3>
</div>
);
}
}
ReactDOM.render(App, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>