Dynamic import doesn't work with combined CRA and SSR - javascript

I've created a website with create-react-app and now I want to use server side rendering because of seo.
After a long research I've found a simple tool here.
It works fine but in my code I have a dynamic import await import("localization/" + newLanguage + "/" + newLanguage + ".json"); and because of that I get a SyntaxError: Unexpected token import error.
I've also tried using System.import. That worked for SSR but CRA says 'System.import' is restricted from being used. Please use import() instead..
How can I solve this problem? I don't want to eject or similiar and hold it easy.
My index.js:
require('ignore-styles');
require('babel-register')({
ignore: /\/(build|node_modules)\//,
presets: ['env','react-app'],
plugins: ["syntax-dynamic-import"]
});
require('./server');
And this is my server file:
import express from 'express';
import http from 'http';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from "react-router";
import App from "./src/App";
const port = 3000;
const app = express();
const server = http.createServer(app);
app.use((req, res) => {
const context = {}
const html = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
if(context.url){
res.status(302).redirect(context.url);
return;
}
res.status(200).send(html);
});
server.listen(port, function(){
console.log('Node server running on port ' + port + '.');
console.log("Time: " + new Date(Date.now()));
});

Ok. I've got it.
I've used the syntax-dynamic-import plugin from babel. With dynamic-import-node from airbnb it works.

Related

Cannot import a function in another file (node.js)

I have an issue that I can't resolve. I'm working with node.js and I simply want to use an export router function in another file .
Here is the code from the import file:
import express from "express";
import * as zoneInstance from "../../controllers/objectInstance/zoneInstance.js";
import { mobilityRouter } from "../../controllers/routerFunction/routerLogic.js";
const router = express.Router();
/* Router for mobility render
// const mobilityRouter = (zone, instance) => {
// return (
// router.get("/mobility/" + zone, instance)
// );
// } */
mobilityRouter(zoneInstance.shoulder.zone, zoneInstance.shoulder.mobilityRender());
Here is the code from the export file:
import express from "express";
const router = express.Router();
// Router for mobility render
export const mobilityRouter = (zone, instance) => {
return (
router.get("/mobility/" + zone, instance)
);
}
// Router for reinforcement render
export const reinforcementRouter = (zone, instance) => {
return (
router.get("/reinforcement/" + zone, instance)
);
}
// Router for proprioception
export const proprioceptionRouter = (zone, instance) => {
return (
router.get("/proprioception/" + zone, instance)
);
}
In the index.js
// Routes for
import mobilityRouter from "./routes/mobility/mobilityAPI.js";
const app = express();
//for mobility URL
app.use("/", mobilityRouter);
When I copy past the 'mobilityRouter' function and use it in the import file it works perfectly, but once I put it in another file and exports it I have a "cannot GET/" in my browser. Thank you for your help.
You have different instances of router in both files. Either pass router as a parameter to the function in the other file or export & import in your routerLogic.js.

Use socket.io with React

How do I use socket.io with React? I have this code for my client:
import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css"
const socket = io()
console.log(socket)
class App extends Component {
render() {
return (
// ...
)
}
}
export default App
And for my server:
const express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http)
io.on("connection", socket => {
console.log("New connection")
})
http.listen(8000, () => {
console.log("Started!")
})
But I keep getting this error:
POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MdZyD8L 404 (Not Found)
What did I do wrong? Thanks.
PS: To launch the app, I do npm run start, and for the server node server/server.js
havn't really ran the code; but, did you notice the port in the error is 3000 rather than 8000 which you initialized the server to listen on?
reading https://socket.io/docs/client-api/, it says that the default is the window location, knowing react, you probably running on port 3000, which is the same 3000 in the error
try setting the port when initializing the socket object
const socket = io("localhost:8000");
Below is the code for connecting through socket if you want that after page is rendered then your socket get connected then write it in componentDidMount.
import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css";
class App extends Component {
componentDidMount(){
let socket = io.connect("http://localhost:8000");
console.log(socket)
}
render() {
return (
// ...
)
}
}
export default App
For example you can go through the link :
https://medium.freecodecamp.org/how-to-create-a-realtime-app-using-socket-io-react-node-mongodb-a10c4a1ab676

Koa.js route() is not a function

I just made simple koa app that returns rss xml by tag using parameter. and seems like middleware can't read router from router file. I have no idea why It doesn't work. I'm running this app.js with babel-node. and It keeps saying this error below
app.use((0, _koaLogger2.default)()).use((0, _routes2.default)());
^
TypeError: (0 , _routes2.default) is not a function
route/index.js
import Router from 'koa-router'
const router = new Router({ prefix: '/'})
router.get('/:tag', async (ctx, next) =>
(ctx.body = await rssGenerator(this.param.tag)))
export default router
app.js
import Koa from 'koa'
import logger from 'koa-logger'
import routes from './routes'
const app = new Koa()
const port = process.env.PORT || 3000
app
.use(logger())
.use(routes())
app.listen(port, () => console.log("[!] Server STARTED"))
I see 2 problems here in your code:
First: you are importing routes like this:
import routes from './routes'
but in your code above the path is route/index.js and not routes
Second: in route/index.js you are exporting router
export default router
but then you are trying to import routes

XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' Google maps

I am new to React js I am trying to simple dynamically changing map with respected to user input But for specific place seach request this error rises
XMLHttpRequest cannot load
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=undef…ined&radius=1000&keyword=fdtbf&key=myapikey.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
this is my node js code
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
//Import To Pord
import api from './routes/api';
import auth from './routes/auth'
import cookieParser from 'cookie-parser';
import {LoginCheck} from './middleware/authCheck';
import cors from 'cors';
//All Webpack Stuff
import webpackConfig from '../../webpack.config.dev';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware'
import webpackHotMidleware from 'webpack-hot-middleware';
//Server Side Rendering Stuff
import {match, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import { dispatch } from 'redux';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import reducer from '../../src/client/Reducers';
import routes from '../client/routes';
import thunk from 'redux-thunk';
import { createStore ,applyMiddleware} from 'redux'
import React from 'react'
import Helmet from 'react-helmet';
import serialize from 'serialize-javascript';
//PassPort Stuff Import This
let app = express();
app.use(bodyParser.json());
app.use(express.static('public'))
const compiler = webpack(webpackConfig);
app.use(webpackMiddleware(compiler, {
hot: true,
publicPath: webpackConfig.output.publicPath,
noInfo: true
}));
app.use(webpackHotMidleware(compiler));
app.use(cors());
app.use(cookieParser('sdkhcvlsd684684JJJklvblsdkuvgblsduvblsidvksdjbvlsjvuywlsfvliusdgv'));
//Check Auth MiddleWare
app.use(LoginCheck)
//Passport Api
app.use('/auth',auth);
//Our Api
app.use('/p',api);
app.get('/*', (req, res,next) => {
// res.sendFile(path.join(__dirname, '../../index.html'))
// Server Side Rendering Starts
match({routes:routes(),location:req.url},(err,redirectLocation,renderProps) => {
if (err) return next(err);
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
}
// if (!renderProps) {
// res.redirect('/404')
// }
const components = renderProps.components;
const Comp = components[components.length - 1].WrappedComponent;
const fetchData = (Comp && Comp.fetchData) || (() => Promise.resolve())
const initialState = {}
const store = createStore(reducer, initialState, applyMiddleware(thunk));
const { location, params, history } = renderProps
fetchData({ store, location, params, history }).then(() => {
const body = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
const state = store.getState();
// console.log(state)
let head = Helmet.rewind();
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.send(`<!DOCTYPE html>
<html>
<head>
${head.title}
${head.meta}
${head.link}
</head>
<body>
<div id="app" >${body}</div>
<script>window.__STATE__=${JSON.stringify(state)}</script>
<script src="/bundle.js"></script>
</body>
</html>`)
})
.catch((err) => next(err))
})
});
app.listen(3000 ,() => {
console.log('Listening')
});
this is my axios request
export function getPlaceFromCoords(term,coords) {
// https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=13.0826802,80.2707184&radius=500&keyword=parks&key=AIzaSyAZbur2hq7p3UxjYrA2_G4ctpswFi0pO3A
console.log(coords)
return dispatch => {
return axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${coords.lat},${coords.lng}&radius=1000&keyword=${term}&key=${config.MAP_API}`).then(response => {
return response.data
})
}
}
The CORS headers are not set for Places API web service on Google backend servers. So you won't be able to call Places API web service from the client side JavaScript code due to the Same-Origin policy of the browsers.
In order to use Places on client side JavaScript you have to use a Places library of Google Maps JavaScript API. The places library has nearby, radar and text search functionality very similar to the corresponding web service.
For further details please have a look at the documentation:
https://developers.google.com/maps/documentation/javascript/places
Hope it helps!

How To Implement React Server Side Rendering With HMR in Webpack2?

I am trying to implement server side rendering with my react app that uses HMR and need some clarification on my issues. There seems to be miscommunication between the server and the frontend but I'm not entirely sure why that is.
When I start my server, the browser loads the client side index.html and I am able to edit my site with HMR working just fine. However, when I navigate to another page besides the homepage, and I refresh the browser, the server then renders the html markup in my handleRender function. The sites html markup appears, however there is no css and HMR doesn't work.
To summarize, on first load, it renders the app client side, but upon refresh, it renders the app server side. I'm thinking it might have to do with the way I am using router.use(express.static(clientDir)); but I'm not sure. Any clarification would be helpful!
Client side Index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Base Template</title>
<link rel="stylesheet" type="text/css" href="/static/bundle.css">
</head>
<body id="body">
<div class="root"></div>
<script src="/static/bundle.js"></script>
</body>
</html>
React App index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
const root = document.querySelector('.root');
// Wraps our App in AppContainer
const render = (Component) => {
ReactDOM.render(
<BrowserRouter>
<AppContainer>
<Component/>
</AppContainer>
</BrowserRouter>,
root
);
};
// Renders our application
render(App);
// Checks if there have been changes and accepts them.
// This activates HMR and refreshes modules in the browser
if (module.hot) {
module.hot.accept();
}
Express Server
import express from 'express'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router'
import { resolve } from 'path'
import routes from './routes'
// Imports our React App
import App from '../client/scripts/App'
// Create Express App
const app = express();
// Set the port for our server
app.set('port', process.env.PORT || 3000)
// Use routes to check if the environment is prod || dev
app.use(routes)
// Use handleRender for SSR
app.use(handleRender)
function handleRender(req, res) {
const context = {};
const html = renderToString(
<StaticRouter location={req.url} context={context} >
<App/>
</StaticRouter>
)
if (context.url) {
res.writeHead(301, {
Location: context.url
})
res.end()
} else {
res.write(`
<!doctype html>
<head>
<title>Redux Universal Example</title>
<link rel="stylesheet" type="text/css" href="/static/bundle.css">
</head>
<body>
<div id="app">${html}</div>
<script type="javascript" src="/static/bundle.js"></script>
</body>
`)
res.end()
}
}
export default app
Routes for server
import express, { Router } from 'express'
import { resolve } from 'path'
import { isDev } from '../utils'
const router = Router();
const clientDir = resolve(`${__dirname}/../../client`);
if (isDev()) {
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpack = require('webpack')
const webpackConfig = require('../../../webpack.config')
const webpackHotMiddleware = require('webpack-hot-middleware')
const compiler = webpack(webpackConfig)
// This compiles our app using webpack
router.use(webpackDevMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath,
noInfo: true
}))
// This connects our app to HMR using the middleware
router.use(webpackHotMiddleware(compiler))
}
router.use(express.static(clientDir));
export default router

Categories