Vue: Proxy requests to a separate backend server with vue-cli - node.js

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.

Related

Network Error while connecting backend to frontend (MERN stack used)

I am making a web app and have made back-end with express, mongodb and node.js, while the frontend is made in React.js.
The backend runs completely fine on its own, when run using "nodemon server.js"
But when connected to frontend using axios, it throws "Network Error" error.
Here is my code to server.js (back-end, connecting url) and http-common.js (front-end, axios)
server.js
import cors from "cors";
import userquery from "./student/api/query.routes.js";
import admin from "./admin/api/admin.routes.js";
const app = express();
app.use(cors());
app.use(express.json());
app.use("/api/v1/user", userquery);
app.use("/api/v1/admin", admin);
app.use("*", (req, res) => {
res.status(404).json({ error: "not found" });
});
export default app;
query.routes.js
import QueryCtrl from "./query.controller.js";
import personalQueriesCtrl from "./personalQueries.controller.js";
import SubjectCtrl from "./subject.controller.js";
import UserCtrl from "./user.controller.js";
const router = express.Router(); //creates routes people can go to
router.route("/").get(QueryCtrl.apiGetQueries);
router.route("/signup").post(UserCtrl.apiPostUser);
router.route("/subjects").get(SubjectCtrl.apiGetSubjects);
router.route("/AskQuery").post(personalQueriesCtrl.apiPostQuery);
export default router;
http-common.js
export default axios.create({
baseURL: "http://localhost:5000/api/v1/user/",
headers: {
"Content-type": "application/json",
},
proxy: false,
});
Please help if you can!

Problems with proxy server in react app with node.js express

I have simple express server in server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
app.get('/express_backend', (req, res) => {
res.send({ "express":"have data"});
});
also component
import { Component } from "react";
import './../css/Rings.css'
import SellItem from "./sellItem";
import Fotter from "./fotter";
class Necklase extends Component{
state ={
data: null
};
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
console.log(body.express)
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render(){
return <div >
<div className="main">
<SellItem/>
</div>
{this.state.data}
<Fotter/>
</div>
}
}
export default Necklase
when i start my react app with npm start in package json npm start looks like this now, also it is proxy
"start": "react-scripts start",
"proxy": "http://localhost:5000",
and after it i start server.js with node server.js in cmd everything work fine, i can get data from response and display it but if i change "start" to this
"start": "react-scripts start && nodemon server.js ",
i got this error in console
Proxy error: Could not proxy request /express_backend from localhost:3000 to http://localhost:5000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
and this when i console.log(body.express) in callBackendAPI
SyntaxError: Unexpected token P in JSON at position 0
can you try with this way
"scripts": {
"start": "nodemon --exec babel-node ./app.js",

How to properly set up Ubuntu 20.04 to deploy a node.js app without caching issues?

I have launched my first node.js app using express.js for the backend and react.js for the frontend. I have it deployed as a background service on a VM with Ubuntu 20.04. The app itself is pretty simple. It makes an API call, gets the latest data and displays it to the enduser in a web browser interface. I initially deployed it on a free Heroku account, where it works fine and always display the latest info from the API call. But when I deployed it on a private VM with Ubuntu 20.04, I noticed that it does not show the latest API info anymore, i.e. it makes the initial API call during npm start and then probably caches it on the server. So, if I come to the app the next day, all the data is from yesterday. To see the latest data, I have to kill the background service on Ubuntu and then do "npm start", which starts the server and makes the API call. I then see the latest data in the browser. This is my first time working with all this technology, so if you have had a similar issue with deploying on Ubuntu, please let me know how I can fix it.
Here is my package.json "scripts":
"scripts": {
"start:dev": "nodemon --exec babel-node server/server.js --ignore public/",
"build": "babel server --out-dir dist",
"start": "node dist/server.js &",
"dev": "webpack -w --mode=development",
"prod": "webpack --mode=production"
}
Here is my server.js code:
import config, { nodeEnv, logStars } from "./config";
import apiRouter from "./api";
import sassMiddleware from "node-sass-middleware";
import path from "path";
import AMdataPullDone from "./AMdataPullDone";
import express from "express";
const server = express();
server.use(
sassMiddleware({
src: path.join(__dirname, "sass"),
dest: path.join(__dirname, "public"),
})
);
server.set("view engine", "ejs");
server.get("/", (req, res) => {
AMdataPullDone.then(({ initialMarkup, initialData }) => {
res.render("index", {
initialMarkup,
initialData,
});
}).catch(console.error);
});
server.use("/api", apiRouter);
server.use(express.static("public"));
server.listen(config.port, config.host, () => {
console.info("Express listening on port ", config.serverUrl);
});
And here is my index.js file with the reach App:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.hydrate(
<App initialData={window.initialData} />,
document.getElementById("root")
);
AMdataPullDone.js code:
import React from "react";
import ReactDOMServer from "react-dom/server";
import App from "./src/components/App";
import generateToken from "./utils/generateToken";
import serverGetAMData from "./serverGetAMData";
const AMdataPullDone = new Promise((resolve, reject) => {
generateToken()
.then(({ access_token }) => {
serverGetAMData(
access_token,
"URL_to_external_API"
)
.then((segResult) => {
const allData = {
initialMarkup: ReactDOMServer.renderToString(
<App initialData={segResult} />
),
initialData: segResult,
};
return resolve(allData);
})
.catch((err) => {
return reject(err.response);
});
})
.catch(console.error);
});
export default AMdataPullDone;
serverGetAMData.js code:
import axios from "axios";
import config from "./config";
const serverGetAMData = async (access_token, apiUrl) => {
const folders = [];
await axios
.get(apiUrl, {
headers: {
Authorization: `Bearer ${access_token}`,
"x-api-key": config.AM_IMS_client_id,
"x-gw-ims-org-id": config.org_id,
}
})
.then((resp) => {
folders.push(...resp.data);
//return resp.data;
})
.catch(console.error);
return folders;
};
export default serverGetAMData;

How to properly configure Next.js as a frontend and Express app as a backend?

Currently I have create-react-app for frontend and express server for backend. In package.json of my create-react-app I use proxy like this "proxy": "http://localhost:5000".
I need to achive the same thing for Next.js app with the same express server.
I just want to be able to use my express server instead of API routes built in Next.js and proxy it like I do in create-react-app.
Do I need to create custom Next.js server even though i'm not changing any of it's functionality? How to do this properly?
yes you have to add custom server in next js
install express js then add file server.js in root directory of next js project
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.use(bodyParser.json())
// add custom path here
// server.post('/request/custom', custom);
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('Ready on http://localhost:5000')
})
})
after that change package.json file script section
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js",
}

Troubleshoot Resolving Express-GraphQL Endpoint with Apollo Client and Proxy Config

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"
},

Resources