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/
Related
How do I create a website with a React Front end and a Flask backend?
I have created websites using flask and templates, and I have made pages using react, and now I would like to combine them.
I have tried a few things and the only things that worked required going into react config files and were very complicated. And even then it was complicated to use fetch and I had to run npm run build every time I changed the react file.
This seems to me like something that would be done all of the time yet I can't find any simple resources to do this.
Is there something that I fundamentally don't understand regarding websites and I am going at this the wrong way?
Focusing on a development workflow, as there are countless choices in how to deploy to a production environment.
Run your Flask app with /api as the root url prefix, either manually by prefixing all your route decorators or with the use of a Blueprint.
py/app.py
#app.route('/api')
def index():
return {'message':'hello'}
Add the Flask development server url to your package.json file
js/package.json
{
...,
"proxy": "http://localhost:5000"
}
Fetch your data using a component
js/Flask.js
import React, { Component } from 'react'
export class Flask extends Component {
constructor(props) {
super(props)
this.state = { data: {}, status: null }
}
fetchData() {
let status
fetch('/api')
.then((res) => {
return {
data: res.json(),
status: status
}
})
.then((data) => {
this.setState({ ...data })
}
.catch((err) => {
console.error(err)
})
}
componentDidMount() {
this.fetchData()
}
render() {
const { data, status } = this.state
return (
<div>
<h3>Status: { status }</h3>
<pre>
{ JSON.stringify(data) }
</pre>
</div>
)
}
}
export default Flask
Finally, include the component in your main App
js/App.js
import React from 'react';
import Flask from './Flask'
function App() {
return (
<div className="App">
<Flask />
</div>
);
}
export default App;
Start your Flask server with your preferred method, either flask run or by executing your script directly, then start your JS development server with either yarn or npm start. You should see the response from your api route displayed at http://localhost:8000
As long as you are running your Flask server with debug=True and use npm start (not npm run build), any changes made with either the backend or frontend will be automatically detected and your app reloaded.
How can i retrieve some data from a local json file i created in my folder? i´m using the following code:
class Intro2 extends Component {
render() {
async function getData() {
const usersData = await fetch("../articles.json");
const users = await usersData.json();
return users;
}
}
This doesn't seem to work for my local json file but if i use a url from git hub users for example its working?
many thanks
The error: main.chunk.js:332 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
You shouldn't be using fetch.
Use import instead. This will ensure webpack doesn't bundle the json file.
But makes it available in the public directory.
const usersData = await import("../articles.json");
Fetch will never work because webpack won't serve your JSON file.
Not unless you put it in a the static or public folder.
I think if you're trying to read from your file system you won't be able to do it, because in at least some browsers, you will need to serve the file via a web server process.
But if you are trying to read from http://localhost:9000/articles.json the issue could be another thing.
Maybe you need the {mode:'no-cors'} param ?
fetch('../static/test.txt', {mode: 'no-cors'})
Else you could simply export it:
export const json = () => ({...})
and then import it to your file:
import {json} from '../json
Assuming the json is in the project's folder structure.
import React from "react";
import ReactDom from "react-dom";
import usersData from "../articles.json";
class Intro2 extends React.Component {
state = {
usersData: { ...usersData },
};
componentDidMount() {
// a place for promises
};
render() {
// where the jsx is rendered
return <div>Renders JSX with state {this.state.usersData.aKey}</div>;
}
};
or with react functional components
// Alternatively, use functional components:
import React from "react";
import usersData from "../articles.json";
function Intro2() {
const [usersData, setUsersData] = React.useState({ ...usersData });
return <div>Renders JSX with state {usersData.aKey}</div>;
}
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";
I have a VPS with Apache + Cpanel.
I can't configure Nginx over it, so the only way, as far as I know, is to 'static export' first then deploy it.
Turns out I can't access the product page by link pasted on url bar directly (not by click a link text).
The link is look like this : www.example.com/products/4 or www.example.com/products/213
My first suggestion is because I 'static export' the project.
I use next-routes with <Link />
My code
import React, { Component } from 'react';
import { withRouter } from 'next/router';
import { connect } from 'react-redux';
import fetch from 'isomorphic-fetch';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import CheckoutBody from '../components/CheckoutBody';
class Product extends Component {
static async getInitialProps({ query }) {
let { id } = { ...query };
if (id === undefined) id = 14;
const res = await fetch(`http://www.example.com/api/product?id=${id}`);
const data = await res.json();
return { campaignDetail: data };
}
render() {
let { lang } = this.props;
return (
<React.Fragment>
<Navbar />
<CheckoutBody
key={this.props.productDetail.id}
productDetail={this.props.productDetail}
lang={lang}
/>
<Footer />
</React.Fragment>
);
}
}
export default Product ;
Same question but different problem: https://github.com/zeit/next.js/issues/9893
I have tried this to .htaccess. It is not working. I am very newbie to regex and htaccess.
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]
What should I do?
Is it what it's called dynamic routes?
The issue might be related to using next export rather than rewrite rule configuration. What we found is nextjs router pathname is not populated with the expected route on first hit if you use next export. Until this issue is fixed within nextjs, you can use a provider in _app.js that wraps your components and adjusts the route or put this before the return statement inside you _app.js default function:
import { useRouter } from 'next/router'
const { asPath, push, pathname } = useRouter()
if (asPath.split('?')[0] != pathname.split('?')[0] && !pathname.includes('[')) {
// Work around for next export breaking SPA routing on first hit
console.log('Browser route ' + asPath + ' did not match nextjs router route ' + pathname)
push(asPath)
return <div>Loading...</div>
}
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;