while importing Routes from routes.js nodemon crash is there any new update regarding the importation of Routes from routes.js??
Index.js code
import express from "express";
//components
import Connection from "./database/db.js";
import Routes from "./routes/Route.js";
const app = express();
app.use("/", Routes);
const PORT = 8000;
Connection();
app.listen(PORT, () =>
console.log(`Server is running successfully on PORT ${PORT}`)
);
Routes.js code
import express from "express";
import {
newConversation,
getConversation,
} from "../controller/conversation-controller.js";
import { addUser, getUser } from "../controller/user-controller.js";
import { newMessage, getMessage } from "../controller/message-controller.js";
const route = express.Router();
route.post("/add", addUser);
route.get("/users", getUser);
route.post("/conversation/add", newConversation);
route.post("/conversation/get", getConversation);
route.post("/message/add", newMessage);
route.get("/message/get/:id", getMessage);
export default route;
Related
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
I'm following this tutorial which I adapt to React Router v4.
I have these files :
auth.js
const express = require('express');
const validator = require('validator');
const router = new express.Router();
function validateLoginForm(payload) {
const errors = {};
let isFormValid = true;
let message = '';
if (!payload || typeof payload.email !== 'string' || payload.email.trim().length === 0) {
isFormValid = false;
errors.email = 'Please provide your email address.';
}
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
isFormValid = false;
errors.password = 'Please provide your password.';
}
if (!isFormValid) {
message = 'Check the form for errors.';
}
return {
success: isFormValid,
message,
errors
};
}
router.post('/login', (req, res) => {
console.log("lol");
const validationResult = validateLoginForm(req.body);
if (!validationResult.success) {
return res.status(400).json({
success: false,
message: validationResult.message,
errors: validationResult.errors
});
}
return res.status(200).end();
});
router.get('/login', (req, res) => {
console.log(req.url);
});
router.get('/', (req, res) => {
console.log(req.url);
console.log("lmao")
});
module.exports = router;
index.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = new express.Router();
// tell the app to look for static files in these directories
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
app.use(bodyParser.urlencoded({extended:false}));
const authRoutes = require('./server/routes/auth');
app.use('/login', authRoutes);
// start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000 or http://127.0.0.1:3000');
});
Base.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { Link, NavLink } from 'react-router-dom';
const Base = ({ child }) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
{child.render()}
</div>
);
Base.propTypes = {
child: PropTypes.object.isRequired
};
export default Base;
and app.jsx
import React from 'react';
import ReactDom from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Base from './components/Base.jsx';
import HomePage from './components/HomePage.jsx';
import LoginPag from './components/LoginPag.jsx';
// for MaterialUI to work properly
injectTapEventPlugin();
const TestLogin = (props) => {
return (<Base child={LoginPag}/>)
};
const TestBase = (props) => {
return(<Base child={HomePage}/>)
};
ReactDom.render((<BrowserRouter><MuiThemeProvider muiTheme={getMuiTheme()}>
<div>
<Switch>
<Route exact path="/" component={TestBase}/>
</Switch>
<Route exact path="/login" component={TestLogin}/>
</div>
</MuiThemeProvider>
</BrowserRouter>), document.getElementById('react-app'));
As you can see, I did a little "workaround" to have everything rendered nicely and it works. But it only works for Client-side routing.
I can't reload pages via f5 or refresh button, nor can I send form and get it through router.post(). It automatically results in a 404 not found.
I printed req.url in router.get('*') to see where the thing goes down and it appears that everywhere I go, the server still receives the address /. I believe the matter is with the <Link to> tag..
How can I fix this and get the server "follow" the client side routing ?
I'm using latest versions of Express, React, and React-Router. Thanks in advance
EDIT : Edited to take into account the remarks made by VivekN
Change your index.js file to the below one:-
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = new express.Router();
// tell the app to look for static files in these directories
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
app.use(bodyParser.urlencoded({extended:false}));
const authRoutes = require('./server/routes/auth');
app.use('/', authRoutes);
// start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000 or http://127.0.0.1:3000');
});
The problem with your code is that you had written when a request comes to your server which has /login in its path, then that should go inside auth.js file and inside that you should check for router.post('/') method.
Either this or you change the index.js file to be
app.use('/', authRoutes);
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
I'm learning to work with the rect, when I try to follow the link, I get such errors:
My client.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import App from '../components/first_page/App';
import {Router, Route } from 'react-router';
import { browserHistory } from 'react-router';
class Main extends Component {
render(){
return (
<Router>
<Route history = {browserHistory}>
<Route path="/f" component={App}/>
</Route>
</Router>
);
}
}
render (<Main />, window.document.getElementById('app'))
App.js
import React, { Component } from 'react';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import { Button } from 'react-bootstrap';
class App extends Component{
render(){
return (
<div>
<Button>Start!</Button>
<Button>Login!</Button>
</div>
);
}
}
export default App
Server
var express = require('express');
var path = require('path');
var config = require('../webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = express()
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));
app.use(express.static(path.resolve(__dirname, './dist')));
app.use('/', function (req, res) {
res.sendFile(path.resolve('client/index.html'));
});
var port = process.env.PORT || 4000;
app.listen(port, function(error) {
if (error) throw error;
console.log("Express server listening on port", port);
});
I tried to pass different tutorials, but always these mistakes are obtained, I will be happy with any help, thanks
I'm having a strange issue when exporting my routes. For some reason, this code works for me:
app.js
import Koa from 'koa'
import routes from './routes/index'
const app = new Koa()
app.use(routes)
app.listen(3000, () => {
console.log('Server listening at http://localhost:3000')
})
export default app
routes/index.js
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
export default router.routes()
but when I just export the routes function and then try to call it in app.js, I get an error:
app.js
import Koa from 'koa'
import routes from './routes/index'
const app = new Koa()
app.use(routes())
app.listen(3000, () => {
console.log('Server listening at http://localhost:3000')
})
export default app
routes/index.js
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
export default router.routes
Why doesn't it work when I do it the second way?
You probably would like to export a bound function, so this inside it would refer to a router object.
It could be done nicely with a bind operator. I believe it's already available since you are using async/await.
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
export default ::router.routes
You have to add a method:
router.allowedMethods()
like this:
app.use(router.routes(), router.allowedMethods())