Now I worked with Node.js + Express to make some api server.
I installed babel-preset-latest to use ES6 statement.
However, When I write some code, it throws error ->
Router.use() requires a middleware function but got a Object
[index.js]
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('main');
});
app.use('/api', require('./api/auth'));
app.listen(3000, () => {
console.log("Express Running port 3000")
})
[/api/auth/index.js]
import express from 'express';
const router = express.Router();
router.get('/', (res, req) => {
res.send('auth main')
});
export default router;
In ES6, module.export can replace to export.
But it throw errors. So, after I replace export default router; to module.exports = router;, It works perfectly.
Why do I get this error? Is there any syntax error?
Thanks.
[SOLVED]
[index.js]
import express from 'express';
import bodyParser from 'body-parser';
import authRouter from './api/auth';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('main');
});
app.use('/api', authRouter);
app.listen(3000, () => {
console.log("Express Running port 3000")
})
[/api/auth/index.js]
import express from 'express';
const router = express.Router();
router.get('/', (res, req) => {
res.send('auth main')
});
export default router;
in index.js, Define import statement -> import authRouter from './api/auth';
and replace app.use('/api', require('./api/auth');
to
app.use('/api', authRouter);
Related
I see that the request sent from the ui created using React is forwarded to the backend, but I can't get the response from the ui. There may be details that I missed as I am very new to these issues, thanks in advance :)
//react Login.js
function Login() {
const fetch = actions.fetchUser();
async function handleSubmit() {
try {
fetch();
} catch (err) {
console.error('err', err);
}
}
export default Login;
//index.js
import axios from 'axios';
export const fetchUser = () => async () => {
await axios.get('/api/login');
};
//setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
['/api'],
createProxyMiddleware({
target: 'http://localhost:5000',
}),
);
};
//express app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(bodyParser.json());
require('./routes/login')(app);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// espress login.js
module.exports = app => {
app.get('/api/login', (req, res) => {
console.error('express login');
res.send('login');
});
First of all, do not mix cjs and mjs import/exports.
second of all, you export your middleware but never register/use it. At least your code does not show that part.
Here is very minimal example how you can proxy your react UI via express.
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();
app.get('/api', (req, res) => {
res.send({my: 'data'});
});
// register other routes here
app.use(proxy('http://127.0.0.1:3000'));
app.listen(5000, '0.0.0.0', () => {
console.log('Server is running at http://127.0.0.1:5000');
});
React app content will be available on http://127.0.0.1:5000 with your routes.
And http://127.0.0.1:5000/api will be your express route.
Note: I assume your react app runs on the port 3000
I need to create a dropdown in order to select languages in the website. I only use nodejs not react. How can I create it? My codes are at the below.enter image description here
const express = require('express');
const app = express();
const ejs = require('ejs');
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const i18nextMiddleware = require('i18next-http-middleware');
i18next
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
fallbackLng: 'tr',
lng: 'tr',
backend: {
loadPath: './translate/{{lng}}.json',
},
});
app.use(i18nextMiddleware.handle(i18next));
app.use(express.json());
app.set('view engine', 'ejs');
const stdI18next = { t: i18next.t.bind(i18next.t) };
app.get('/', (req, res) => {
res.render('index', stdI18next);
});
app.get('/test', (req, res) => {
res.render('test', stdI18next);
});
Overview
I am trying to get authentications set up in Apollo but I keep running into this network error: CORS error PreflightAllowOriginMismatch. I have looked and tried so many solutions on the internet but nothing is working.
I have my client running on localhost:3000 and my server on localhost:4000.
Code
//client index.js
import React from 'react';
import { render } from 'react-dom';
import { ApolloProvider } from '#apollo/client';
import App from './App';
import { ApolloClient, createHttpLink, InMemoryCache } from '#apollo/client';
const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include',
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
render((
<ApolloProvider client={client}>
<App />
</ApolloProvider>
), document.getElementById('root')
);
//server index.js
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const cors = require('cors');
const schema = require('./schema');
const models = require('./sequelize/models');
const server = new ApolloServer({
schema,
context: req => ({
...req,
models,
})
});
const app = express();
var corsOptions = {
origin: 'http://localhost:3000/',
credentials: true // <-- REQUIRED backend setting
};
app.use(cors(corsOptions));
server.applyMiddleware({ app, cors: false });
app.listen({ port: 4000 });
I'm honestly lost at this point. I new to apollo and for the life of me cannot find what i am missing.
Although I am unsure about the security the following changes fixed my issue.
remove
origin: 'http://localhost:3000/',
credentials: true // <-- REQUIRED backend setting
};
app.use(cors(corsOptions));
update
server.applyMiddleware({ app, cors: {credentials: true, origin: true} });
the final file:
//server index.js
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const schema = require('./schema');
const models = require('./sequelize/models');
const server = new ApolloServer({
schema,
context: req => ({
...req,
models,
})
});
const app = express();
server.applyMiddleware({
app,
cors: {credentials: true, origin: true}
});
app.listen({ port: 4000 });
I am trying to pass some data to my serverMiddleware using axios but I can't seem to be able to get the data in my serverMiddleware
guilds page script:
<script>
export default {
async fetch() {
const token = 'testToken'
const guilds = await this.$axios.$post('/api/guilds', { token })
}
}
</script>
serverMiddleware:
import axios from 'axios'
import express from 'express'
const router = express.Router()
const app = express()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})
router.post('/', (req, res) => {
console.log(req)
})
export default {
path: '/api/guilds',
handler: router
}
Token should be an object of key-value.
async fetch() {
const token = 'testToken'
const guilds = await this.$axios.$post('/api/guilds', { token: token })
}
Then you can take it from req.body in serverMiddleware.
I am hoping this is a simple question. I have an express server with one route.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/src/index.html'));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
The index.html links to the js below:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router';
import Redux from 'redux';
var App = React.createClass({
render: () => {
return(
<div>React!
<Link to={`/page2`}>Page 2</Link>
</div>
);
}
});
var AnotherView = React.createClass({
render: () => {
return(
<div>Page 2
<Link to={`/`}>App</Link></div>
);
}
});
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}></Route>
<Route path="/page2" component={AnotherView}/>
</Router>,
document.getElementById('app')
);
I can click the links and the urls change when I go to localhost:3000 and start from there. The question is this, what should happen if I go to localhost:3000/page2 when using the router? Is it supposed to figure out that its supposed to show the AnotherView component and show it? I am getting "Cannot GET /page2" from express. If it is what do I need to do to make it do that?
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname + '/src/index.html'));
});
The server should handle all the request, not only '/'.