I'm attempting to connect to an Express-GraphQL endpoint in a Create-React-App using Apollo Client with a custom proxy config for development. I receive the following error: .
Apollo Client Network Interface:
import {ApolloProvider, ApolloClient, createNetworkInterface} from 'react-apollo';
import './index.css';
const client = new ApolloClient({
networkInterface: createNetworkInterface({
uri:"http://localhost:8080/graphql",
}),
connectToDevTools: true
});
Express Server / GraphQL Server
const graphqlHTTP = require('express-graphql');
const app = express();
app.use('/graphql', graphqlHTTP(request =>{
return {
schema: schema,
graphiql: true,
rootValue: root
} }));
let server;
function runServer(dbUrl, host, port=3001) {
return new Promise((resolve, reject) => {
mongoose.Promise = global.Promise;
mongoose.connect(dbUrl, err => {
if (err) {
return reject(err);
}
server = app.listen(port, host, () => {
console.log(`Your app is listening on port ${port}`);
resolve();
})
The Proxy
(With http-proxy-middlewear)
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
const runServer = require('./server').runServer;
const app = express();
// Proxy everything through to Create React App
app.use(proxy('http://localhost:3000/', {
logLevel: 'warn', // Keep the logs clean
ws: true, // Proxy websockets too
router: {
// Anything to /api goes to our backend
'http://localhost:8080/graphql': 'http://localhost:3001/',
}
}));
app.listen(8080);
Top Level package.json aka The Reason
(3 package.json's for client, server, and top level)
"scripts": {
"start": "node index.js",
"heroku-postbuild": "cd client && npm install --only=dev && npm run build",
"dev": "run-p dev:server dev:client start",
"dev:client": "cd client && cross-env BROWSER=none npm start -- --color=always | xp http://localhost:3000/ http://localhost:8080/",
"dev:server": "cd server && npm start",
"install": "run-s install:server install:client",
"install:server": "cd server && npm install",
"install:client": "cd client && npm install"
},
Related
Trying to configure proxy in react native with node to run axios calls.
Tried the following code in server/package.json
"proxy": {
"/*": {
"target": "http://localhost:5000/"
}
},
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "cd ../client && yarn ios",
"dev": "concurrently \"yarn server\" \"yarn client\""
}
server/authRouter.js
const authRouter = require('express').Router();
authRouter.get('/test', (req, res) => {
res.send('proxy success');
});
module.exports = authRouter;
server/index.js
const express = require('express');
const authRouter = require('./authRouter');
const app = express();
app.use('/auth', authRouter);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
client/app.js
await axios.get('/auth/test');
When I run yarn dev and test an axios call, it logs the following error
LOG [Error: Network Error]
any help would be much appreciated.
Try calling the proxy directly in axios
http://localhost:5000/auth/test
I'm not sure why it doesn't work that way, even i had a problem in the past.
I'm running Nuxt in Universal Mode with Koa as API / Controller in the backend based on the Koa template. I'm deploying to Heroku. API works fine locally, but returns 404 in production. I think that the app is running as SPA when deployed as everything else works well.
Here's my server/index.js
const Koa = require('koa')
const consola = require('consola')
const Router = require('koa-router');
const { Nuxt, Builder } = require('nuxt')
const api = require('./api');
console.log('server works'); // ------> This line gets ignored by the Heroku console
const app = new Koa()
const router = new Router();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'
router.use('/api', api.routes(), api.allowedMethods());
app.use(router.routes());
async function start () {
// Instantiate nuxt.js
const nuxt = new Nuxt(config)
const {
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000
} = nuxt.options.server
// Build in development
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
app.use((ctx) => {
ctx.status = 200
ctx.respond = false // Bypass Koa's built-in response handling
ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res)
})
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`, // ------> Neither this line appears in Heroku console
badge: true
})
}
start()
Procfile
web: nuxt start
Scripts from package.json
"scripts": {
"dev": "cross-env HOST=192.168.1.65 NODE_ENV=development nodemon server/index.js --watch server ",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate",
"test": "ava",
"test:unit": "cross-env TEST=unit ava --config unit.config.js",
"test:e2e": "cross-env TEST=e2e ava --config e2e.config.js",
"heroku-postbuild": "nuxt build"
}
I think I'm getting nu(x)ts after reading all these deployment docs and not seeing the obvious.
Thanks.
I didn't live any problem, attaching my package.json, server/index.js file and Heroku environment settings. You can check herokuapp from here
package.json
{
"name": "testkoa",
"version": "1.0.0",
"description": "My first-class Nuxt.js project",
"author": "Ahmet Zeybek",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate"
},
"dependencies": {
"#nuxtjs/axios": "^5.3.6",
"#nuxtjs/dotenv": "^1.4.0",
"#nuxtjs/pwa": "^3.0.0-0",
"cross-env": "^5.2.0",
"koa": "^2.6.2",
"koa-router": "^7.4.0",
"nuxt": "^2.0.0"
},
"devDependencies": {
"nodemon": "^1.18.9"
}
}
server/index.js
const Koa = require("koa");
const Router = require("koa-router");
const consola = require("consola");
const { Nuxt, Builder } = require("nuxt");
const app = new Koa();
// Import and Set Nuxt.js options
const config = require("../nuxt.config.js");
config.dev = app.env !== "production";
async function start() {
app.use(async function handleError(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = err;
}
});
const router = new Router({ prefix: "/api" });
router.get("/:name", async ctx => {
ctx.response.body = `Hello ${ctx.params.name}`;
});
// Instantiate nuxt.js
const nuxt = new Nuxt(config);
const {
host = process.env.HOST || "127.0.0.1",
port = process.env.PORT || 3000
} = nuxt.options.server;
// Build in development
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
app.use(router.routes());
app.use(router.allowedMethods());
app.use(ctx => {
ctx.status = 200;
ctx.respond = false; // Bypass Koa's built-in response handling
ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res);
});
app.listen(port, host);
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
});
}
start();
Heroku Config Vars
HOST=0.0.0.0
NODE_ENV=production
NPM_CONFIG_PRODUCTION=false
You don't need Procfile to use your Nuxt app on Heroku with this
configuration, remove it from your project folder
I am trying to deploy my app which using node.js, react and MongoDB to Heroku; The deploy was succeeded; However, the website cannot fetch data from MongoDB.
The error is GET http://localhost:5000/comment net::ERR_CONNECTION_REFUSED and Uncaught (in promise) Error: Network Error, I think it is because I don't have node server.js running in the backend. can anyone help me with how to deploy this correctly?
my pakage.json in the backend is
"client-install": "npm install --prefix myprofile",
"start":"node server.js",
"server":"nodemon server.js",
"client":"npm start --prefix myprofile",
"dev":"concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild":"NPM_CONFIG_PRODUCTION=false npm install --prefix myprofile && npm run build --prefix myprofile"
}
And my server.js is
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
//app.use(express.static(path.join(__dirname,'./myprofile/build')));
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB data connected");
});
const CommentRouter = require("./CommentRouter");
app.use("/comment", CommentRouter);
if (process.env.NODE_ENV === "production") {
app.use(express.static("myprofile/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "myprofile", "build", "index.html"));
});
}
app.listen(port, () => console.log(`Server is running on ${port}`));
Thank you very much in advance!
If you are deploying this project to heroku, your start command and your server.js looks similar to this example so that's a good start.
Are you setting your environment variables with heroku, specifically process.env.ATLAS_URI? I would imagine heroku doesn't know where your MongoDB database is located.
Im trying to deploy a nodejs and react app to Heroku. It works completely fine local and it does serve my backend, but i get Not Found on anything else than my api endpoints. It seems like its not running the build script in the client folder. Can anyone help me spot where it goes wrong?
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const projects = require('./routes/api/projects');
const app = express();
// Body parser middlewaree
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
// Connect to DB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log('mongoDB connected.'))
.catch(err => console.log(err));
// Setting up routes
app.use('/api/projects', projects);
// Serve static assets if in production
app.use(express.static(path.join(__dirname, '/client/build')));
app.get('*', (req, res) => {
res.sendfile(path.join((__dirname, '/client/build/index.html')));
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server up and running on ${port}`));
package.json
"scripts": {
"client-install": "npm install --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
I've deployed successfully to Heroku using the following code (I've just answered an alike question here):
app.use(express.static(path.join(__dirname, './client/build')))
app.get('*', function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
Also, if you're trying to deploy a create-react-app application, you can use this buildpack. Buildpacks are scripts that are run when your app is deployed. They are used to install dependencies for your app and configure your environment.
You can see the full code here of how I usually deploy Heroku applications.
I am using vue-cli webpack template to generate my projects, and I'd like to proxy requests to a separate, backend server. But I got the error message as follow.
Could anyone tell me what's the matter with my coding?
Thank you very much!
Error message
[HPM] Error occurred while trying to proxy request from localhost:8080 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
config -> index.js
proxyTable: {
'/api':{
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
src -> main.js
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import routerConfig from './router.config.js'
import Axios from 'axios'
Vue.config.productionTip = false;
Vue.prototype.$axios = Axios;
Vue.prototype.HOST = '/api';
Vue.use(VueRouter);
const router = new VueRouter(routerConfig)
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
})
src -> App.vue
export default{
created(){
var url = this.HOST
this.$axios.get(url,{
}).then((res)=>{
console.log(res.data)
},(res)=>{
alert(res.status)
})
}
}
server
const express = require('express');
const mysql = require('mysql');
const db = mysql.createPool({
localhost:'localhost',
user:'root',
password:'123456',
database:'blog'
})
const server = express();
server.use('/api',(req,res)=>{
db.query(`SELECT * FROM articles_table`,(err,data)=>{
if(err){
console.error(err);
res.status(500).send('database error').end();
}else{
res.send(data)
}
})
})
server.listen(3000)
Do as follows:
npm install --save-dev concurrently
Add to scripts at package.json:
"server": "node server.js",
"go": "concurrently --kill-others \"npm run dev\" \"npm run server\""
And use, from now on:
npm run go
Naturally, you can rename go to whatever you want.