I am following a tutorial to learn ReactJS, i am trying to create Spring Boot and React Java Full Stack Application with Maven.
Below are the files which i created:
App.js
import React, { Component } from "react";
import "./App.css";
import InstructorApp from "./component/InstructorApp";
class App extends Component {
render() {
return (
<div className="container">
<InstructorApp />
</div>
);
}
}
export default App;
ListCoursesComponent.jsx:
import React, { Component } from "react";
import CourseDataService from "../service/CourseDataService";
class ListCoursesComponent extends Component {
constructor(props) {
super(props);
this.refreshCourses = this.refreshCourses.bind(this);
}
componentDidMount() {
this.refreshCourses();
}
refreshCourses() {
CourseDataService.retrieveAllCourses(INSTRUCTOR) //HARDCODED
.then(response => {
console.log(response);
});
}
}
export default ListCoursesComponent;
InstructorApp.jsx:
import React, { Component } from "react";
import ListCoursesComponent from "../component/ListCoursesComponent";
class InstructorApp extends Component {
render() {
return (
<>
<h1>Instructor Application</h1>
<ListCoursesComponent />
</>
);
}
}
export default InstructorApp;
CourseDataService.js:
import axios from "axios";
const INSTRUCTOR = "in28minutes";
const COURSE_API_URL = "http://localhost:8080";
const INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}`;
class CourseDataService {
retrieveAllCourses(name) {
return axios.get(`${INSTRUCTOR_API_URL}/courses`);
}
}
export default new CourseDataService();
When i am lunching my application, in the tutorial i am supposed to get the below error:
[Error] Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load http://localhost:8080/instructors/in28minutes/courses due to access control checks.
[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. (courses, line 0)
[Error] Unhandled Promise Rejection: Error: Network Error
(anonymous function) (0.chunk.js:1097)
promiseReactionJob
But when i am lunching my application i am getting this error:
./src/component/ListCoursesComponent.jsx
Line 15:42: 'INSTRUCTOR' is not defined no-undef
Search for the keywords to learn more about each error.
The unhandled promise rejection means that at some point the request was made to call your url, but it was denied, this is probably because you need to activate CORS into your project. You can read more about CORS and adding it to your project here.
You declared INSTRUCTOR in ListCoursesComponent.jsx but you are trying to use it in a different file. If you want to do this you need to export it where you define it and import it in the file you are using it.
Solution:
As mentioned by #emoore i have added the CORS in my springboot backed application by:
#CrossOrigin(origins = { "http://localhost:3000", "http://localhost:4200" })
#RestController
As mentioned by #trixn i imported INSTRUCTOR Const in the ListCoursesComponent file by:
import INSTRUCTOR from "../service/CourseDataService";
Related
i'm trying to access express.js routes from react front end but i don't seem to get how to go about it. my express.js backend runs on localhost:9000 and my react frontend runs on localhost:3000. this is my react code;
import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: "" };
}
callAPI() {
fetch("http://localhost:9000/:username")
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount() {
this.callAPI();
}
render(){
return (
<div className="App">
<p>{this.state.apiResponse}</p>
</div>
);
}
}
export default App;
i have created two files on express routes folder, one is testAPI.js and the other is be.js. when i try to acces any of these two files from my browser without using react, on lets say localhost:9000/testAPI it works fine. but when i try to access localhost:3000/testAPI which calls the same file through react, it gives me this messed up error page:
<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Not Found</h1><h2>404</h2><pre>NotFoundError: Not Found at C:\Users\Denoh\full\api\app.js:33:8 at Layer.handle [as handle_request] (C:\Users\Denoh\full\api\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:317:13) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:275:10) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:635:15 at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:260:14) at Function.handle (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:47:12)</pre></body></html>
please assist
you need to use proxy in package.json to achieve this
basically you set the url you want to proxy too so that React knows how to connect to your server
see this for more info: https://create-react-app.dev/docs/proxying-api-requests-in-development/
I am working on react, when i am trying to use const app_url i am getting error, in this line i am getting error import MobileEsp from app_url+'/js/mdetect.js'; it is because of app_url, here is my full code of it, can anyone please help me to resolve this issue ?
Error :
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /var/www/minimal-react-webpack-babel-setup/src/App.js: Unexpected token (6:22)
Code
import React from 'react';
const app_url = 'https://*******.com/';
import $ from "jquery";
import MobileEsp from app_url+'/js/mdetect.js';
//const App = ({ title }) =>
class App extends React.Component {
componentDidMount() {
if (!MobileEsp.DetectTierIphone() && !MobileEsp.DetectTierTablet()) {
var LinkDownloadAppMac1 = "*****";
var LinkDownloadAppWin1 = "******";
switch (navigator.platform) {
case 'MacIntel':
$('#menu-download-link').attr('href', LinkDownloadAppMac1);
break;
default:
$('#menu-download-link').attr('href', LinkDownloadAppWin1);
break;
}
}
}
I don't think this is a legal syntax. even in modern JavaScript/ES6 JavaScript and beyond. This is because JavaScript dependency imports have to be statically resolved.
However, you can dynamically import the dependency within your component.
For instance, you can import it within your ComponentDidMount lifecycle hook.
async ComponentDidMount() {
const appUrl = 'https://*******.com/';
const MobileEsp = await import(`${appUrl}/js/mdetect.js`);
// do the rest here
}
Error im recieveing in the console.log
[14:02:02] [Unhandled promise rejection: Error: Network Error]
- node_modules\axios\lib\core\createError.js:16:24 in createError
- node_modules\axios\lib\adapters\xhr.js:87:25 in handleError
- ... 9 more stack frames from framework internals
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
import PhotoSection from './photo-section';
//functional is just returning some data - static
//smart component for dynamic class component
export default class PhotoFeed extends Component {
render() {
axios.get('http://127.0.0.1:3000/photos')
.then(response=> console.log(response));
return (
<View>
<Text> textInComponent </Text>
</View>
);
}
}
The development server returned response error code: 500 \n\n
Unable to resolve "./components/Provider" from "node_modules\react-redux\lib\index.js"
BodyX:
{"originModulePath":"C:\\Users\\MY PC\\Documents\\Projects\\snapfood-customer\\node_modules\\react-redux\\lib\\index.js","targetModuleName":"./components/Provider","message":"Unable to resolve module `./components/Provider` from `C:\\Users\\MY PC\\Documents\\Projects\\snapfood-customer\\node_modules\\react-redux\\lib\\index.js`: The module `./components/Provider` could not be found from `C:\\Users\\MY PC\\Documents\\Projects\\snapfood-customer\\node_modules\\react-redux\\lib\\index.js`. Indeed, none of these files exist:\n\n
my code is as below:
import React from 'react';
import store from './app/index';
import WelcomeScreen from './app/WelcomeScreen';
import { Provider } from 'react-redux';
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<WelcomeScreen/>
</Provider>
);
}
}
SnapSVG extension for Adobe Animate.cc 2017 is able to create interactivity and animations for the web. I'm currently trying to use an exported SnapSVG Adobe Animate.cc project in my REACT JS WebApplication.
What I've done so far:
Imported snapsvg-cjs from npm( modified snapsvg to use succesfull in React)
Imported axios to load custom json file generated from SnapSVG extension in Animate.cc
Excluded minified code with eslintignore from SnapSVGAnimator. lib, generated while publishing SVG animation from Animate.cc to work properly without the ESlinting warnings.
Create a componentDidMount function
current code:
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { SVGAnim } from './SnapSVGAnimator.js';
import snapsvg from 'snapsvg-cjs';
componentDidMount(){
axios.get(jsonfile)
.then(response => {
const json = response.request.responseText;
const comp = new SVGAnim(json);
console.log(comp)
});
}
Problem
Following error appears while I log const comp.
Uncaught (in promise) TypeError:
_SnapSVGAnimator.SVGAnim is not a constructor
During the publish render in Animate.cc there are two libs generated; snapsvg.js and SVGAnimator.js
You can import snapsvg-cjs from NPM but SVGAnimator.js isn't available. Importing SVGAnimator.js with the ES6 approach from a curtain directory in your ReactApp isn't possible, not even by excluding it from linting with /* eslint-disable */ 1000 warnings still appears.
Instead of that, add the code to your index.html file, located in the public folder this way
(I've used create-react-app to build this project):
<script type="text/javascript" src="%PUBLIC_URL%/libs/SnapSVGAnimator.min.js"></script>
This is the working code:
import React, { Component } from 'react';
//axios for asnyc usage*/
import axios from 'axios';
//Snapsvg-cjs works out of the box with webpack
import Snapsvg from 'snapsvg-cjs';
//snap.json is located in the public folder, dev-build folder(ugly approach).
let jsonfile = "snap.json";
class SVGAnimator extends Component {
constructor(props){
super(props);
this.state = {
data: ''
}
}
componentDidMount(){
axios.get(jsonfile)
.then(response => {
this.setState({ data: response.data })
});
}
getSVG(){
if(this.state.data){
const container = document.getElementById('container');
const SVG = new window.SVGAnim(this.state.data, 269, 163, 24)
container.appendChild(SVG.s.node);
}
}
render() {
return (
<div id="container">
{ this.getSVG()}
</div>
);
}
}
export default SVGAnimator;