I have a vue app I'm trying to connect to a flask api, all running on different ports on the same machine. My vue.config.js looks like this:
module.exports = {
// options...
devServer: {
public: 'localhost',
disableHostCheck: true,
proxy: {
'^/flask': {
target: 'http://localhost:8001',
pathRewrite: {'^/flask': '/'},
changeOrigin: true,
logLevel: "debug",
},
'/V2': {
target: 'http://localhost:8001',
changeOrigin: true,
pathRewrite: {'^/V2': ''}
},
}
}
}
where port 8001 is the port the flask is running on. Except the actual api requests from vue are being sent to port 9600 (and failing). For example:
fetchData() {
const path = '/flask/search';
console.log('Homepage recieved query')
if (this.queryform !== 'initVal') {
axios.post(path, this.queryform)
.then((res) => {
this.queryResult = res.data;
console.log('Homepage recieved results');
})
.catch((error) => {
console.log(error);
});
}
},
results in the error "Proxy error: Could not proxy request //search from ****:8002 to http://localhost:9600 (ECONNREFUSED)." *** is the ip address, omitting for privacy sake.
I know this an error within vue, I'm able to successfully use all the api routes on the flask app using my api testing program.
I can't find anywhere in the code where requests are sent to :9600, is there another configuration file I need to change?
Related
I'm learning programming now so forgive me for any mistakes, I'll be grateful for any tips.
I have an API that is hosted in the following domain ("api-myapp.com") and I'm trying from my localhost where I'm creating my front-end to post a form (which only logged in users can send) using axios , but the request takes a long time to complete and when it completes it returns the following error (No 'Access-Control-Allow-Origin' header is present on the requested resource.)
(net::ERR_FAILED 504), I've tried some solutions I found on the internet but none seem to have worked, this is my code:
FrontEnd:
try {
const response = await axios.post('/alunos/', {
nome,sobrenome,idade,sangue,varinha,patrono,house,sala,
});
toast.success('Cadastrado com sucesso');
console.log(response);
} catch (e) {
console.log(e);
const errors = get(e, 'response.data.errors', []);
errors.map((error) => toast.error(error));
}
When you logged in
try {
const response = yield call(axios.post, '/tokens', payload);
yield put(actions.loginSuccess({ ...response.data }));
axios.defaults.headers.Authorization = `Bearer ${response.data.token}`;
toast.success('Login realizado com sucesso!');
payload.navigate('/dashboard');
}
BackEnd
class App {
constructor() {
this.app = express();
this.middlewares();
this.routes();
}
middlewares() {
this.app.use(cors({ origin: '*' }));
this.app.use(helmet({ crossOriginResourcePolicy: false }));
this.app.use(express.urlencoded({ extended: true }));
this.app.use(express.json());
this.app.use('/images/', express.static(resolve(__dirname, '..', 'uploads', 'images')));
}
routes() {
this.app.use('/', homeRoutes);
this.app.use('/prof', profRoutes);
this.app.use('/tokens', tokenRoutes);
this.app.use('/alunos', alunoRoutes);
this.app.use('/casas', casaRoutes);
this.app.use('/provas', provaRoutes);
this.app.use('/materias', materiaRoutes);
this.app.use('/salas', salaRoutes);
this.app.use('/fotosAlunos', fotoAlunoRoutes);
this.app.use('/fotosProf', fotoProfRoutes);
}
}
You have to enable CORS in backend to allow request through different ports.
For your case since you are using express and cors library, you can try this.
app.use(
cors({
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
allowedHeaders: ['Content-Type', 'Authorization'],
origin: ['http://localhost:3000', 'http://localhost:3030'], // whatever ports you used in frontend
})
);
I have a React App that is deployed on Netlify and a GraphQL/express backend deployed on Heroku.
I use the connect.sid cookie to the server to persist login and handle other backend requests e.g. stripe payments. The cookie is generated in my local development environment; however, in production (server + postgres db deployed on Heroku + client deployed on Netlify) the connect.sid cookie is not sent back to the client.
However, when viewing the Heroku logs, I can tell that the cookie is being generated. It is just not usable or visible by the client.
Here is my node server:
const startServer = async () => {
if (typeOrmOptions.url) {
await createConnection(typeOrmOptions); // --> was this before
} else {
await createConnection(); // --> was this before
}
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }: any) => ({ req }),
introspection: true,
playground: true
});
const app = express();
const forceSsl = function(req, res, next) {
if (req.headers["x-forwarded-proto"] !== "https") {
return res.redirect(["https://", req.get("Host"), req.url].join(""));
}
return next();
};
app.use(forceSsl);
app.set("trust proxy", 1);
app.use(
session({
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 86400000,
domain
},
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
}),
secret: "keyboard cat"
})
);
server.applyMiddleware({
app,
cors: {
origin: webUrl,
credentials: true
}
});
app.listen({ port: port }, () =>
console.log(
`🚀 Server ready at http://localhost:${port}${server.graphqlPath}, weburl = ${webUrl}`
)
);
};
startServer();
Here is the React client
const serverUrl =
process.env.NODE_ENV === "development"
? "http://localhost:4000"
: "https://server-domain.com";
const client = new ApolloClient({
uri: `${serverUrl}/graphql`,
credentials: "include"
});
function App() {
console.log(serverUrl, "uri");
return (
<ApolloProvider client={client}>
<ThemeProvider theme={theme}>
<Routes/>
</ThemeProvider>
</ApolloProvider>
);
}
export default App;
Output of the Network on localhost
Output of the cookie on localhost
Output of the Network in production
Output of the cookie (or lack thereof) in production
Output of the console in production
Output of the Heroku logging
As you can see, the sessions are being logged server side ... they just aren't making it to the client.
Banging my head against the wall -- would appreciate any help!
Any suggestions on how to fix this?
I've got problem with proxy in react app.
Target: I've got two react apps, first app is on localhost:3000 and second on localhost:3001. What I want? => When in first app I'll click on:
<a href="/app2">
<button>Second App Open</button>
</a>
Then url will change from localhost:3000 into localhost:3000/app2 and second react app show what has got in url localhost:3001.
I imported http-proxy-middleware library and create in src direction file setupProxy.js and inside:
const {createProxyMiddleware} = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
createProxyMiddleware('/app2',{
target: 'http://localhost:3001',
changeOrigin: true,
prependPath: false,
secure: false,
logLevel: 'debug',
ws:true
})
);
app.listen(3000)
};
Anyone could help me with this?
Also I tried this code in setupProxy.js:
const express = require('express')
const {createProxyMiddleware} = require("http-proxy-middleware");
app = express()
app.use(
createProxyMiddleware('/app2',{
target: 'http://localhost:3001',
changeOrigin: true,
prependPath: false,
secure: false,
logLevel: 'debug',
ws:true
})
);
app.listen(3000)
But then I've received error that require(...) is not a function oraz that express is not a function, when I take express into {} then also occurs error.
I know it's late and I came across the same issue. Keeping what worked for me so that others can give it a try.This code is tested for react app created with create-react-app.
I proxied this endpoint - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(createProxyMiddleware('/api2', {
target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
changeOrigin: true,
pathRewrite: { '^/api2': '' }
})
);
}
Your .js file
triggerCORSCall() {
axios.get(`/api2/Customers?$format=json`)
.then(response => {
alert('Success');
}).catch(error => {
alert('Failure');
console.log(error);
})
}
I am using the http-proxy-middleware module, which is an express middleware. the middleware module relies on http-proxy. The node host is running behind a proxy.
I want to forward certain routes to a different service (for test purposes let's assume httpbin.org). So I defined the proxy as follows.
var proxy = require('http-proxy-middleware');
var aeProxy = proxy({
target: 'http://httpbin.org',
changeOrigin: true,
pathRewrite: {
'^/api/ae':'/get'
}
});
app.use('/api/ae', proxy);
I have also set the respective env variables (from debugging console):
process.env.HTTP_PROXY
> "http://proxy:8080"
process.env.HTTPS_PROXY
> "http://proxy:8080"
Unfortunately I only get timeouts. When running the node script in an environment without a proxy it works as expected.
Is my configuration wrong?
Credit to chimurai for this on how to connect via a corporate proxy via the agent field.
var HttpsProxyAgent = require('https-proxy-agent');
var proxy = require("http-proxy-middleware");
// corporate proxy to connect to via environment variables
var proxyServer = process.env.HTTPS_PROXY ||
process.env.HTTP_PROXY;
var options = {
target: 'http://localhost:3000',//Proxy url
agent: new HttpsProxyAgent(proxyServer)//The actual corporate proxy sever
};
var apiProxy = proxy('/api', options);
If you are behind a V2Ray protocol, you can just set the listening address and port of your connection like bellow and you'r good to go.
var HttpsProxyAgent = require('https-proxy-agent');
const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: process.env.REACT_APP_API_URL
changeOrigin: true,
secure: false,
logLevel: "debug",
onProxyReq: fixRequestBody,
agent: new HttpsProxyAgent('http://127.0.0.1:1087'),
headers: {
'X-Auth-Token': process.env.REACT_APP_API_TOKEN
},
pathRewrite: {
'^/api': ''
}
})
);
};
I have a node.js application where one of the views is a ghost.js blog, which I integrated by following Ghost's wiki article Using Ghost as an npm module.
Currently, my local version works perfectly.
The Error:
When I visit the deployed website, everything works ok, except when I got to mysite.heroku.com/blog, at which point I get the ghost page looking like .
I've noticed that the application has two localhost branches running simultaneusly (localhost:3000 and localhost:2368/). I'm not sure if that could be causing the error. I've checked out my Herokulogs, and they do not provide any more details than that a GET request was sent to /blog, returning first a 301and then a 404 error.
Also, it might be useful to know that when I click on the Go to front page link it sends me to http://localhost:2368/
My config.js file looks like the following:
var path = require('path'),
config;
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://example.com/blog',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
// Change this to your Ghost blogs published URL.
url: 'http://localhost:2368/blog',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
// Export config
module.exports = config;
It looks like Ghost is configured via a config.js file (see the link you provided), and that you may have it configured for url: 'http://localhost:2368/blog'. Looks like you'll need to change that to your actual URL.
Also, see this https://github.com/cobyism/ghost-on-heroku