I have been using SpringBoot for web development before, which needs to manage session, database, HTML and other functions.
Recently, I am going to use VUE, replacing the HTML part of SpringBoot.
Now I use the following two methods for development, but I am troubled by problems such as cross domain and session cannot be keeped.
Use nodejs as the enter of the website and use vue.config to configure the agent. In this way, the URL located is correct, but the login status cannot be saved.For example, if submit a form for login, the background returns to the successful message for login, but if refresh the page, it will show 'not login'. The 'devServer' configuration is as follows
devServer: {
open: false,
host: 'localhost',
port: 8080,
proxy: {
'/ API: {
Target: 'http://192.168.9.211/',
ChangeOrigin: true,
ws: true,
PathRewrite: {
'^ / API' : ' '
},
cookieDomainRewrite: 'localhost',
}
}
}
Use Nginx as gateway, and then forward the HTML request to NodeJS, and the data request (such as JSON data) to SpringBoot.I haven't had time to experiment with this idea, because it may still occur session saving issues.Nginx is forwarding HTTP requests to Nodejs and SpringBoot, so this saved session is from Nodejs or SpringBoot?
So ask if anyone has done a similar project and if you can share your experience.
Related
I need to set up a simple replication schema with a secondary database. I figured out that using arangosh I can set it up with the following commands:
db._useDatabase("myDB");
require("#arangodb/replication").setupReplication({
endpoint: "tcp://main-server:8529",
username: "user",
password: "pass",
verbose: false,
includeSystem: false,
incremental: true,
autoResync: false,
autoStart: true,
restrictType: "include",
restrictCollections: [ "Products" ]
});
This setup, however does not seem to persist. Connection going down, or server restarts make it disappear.
So, I would like to set up some monitoring and re-establishment of the replication in my Go program.
I searched both the ArangoDB website Manual pages, and Go driver documentation but I could not find anything that would allow me to run the above setup in Go using the driver.
Additionally, I didn't find how I could interface with arangosh, and possibly run the JS code above and get the results. Is that possible somehow using the Go driver?
I accidentally found a solution to this.
The Golang driver does not provide this functionality. But Arango has a pretty simple HTTP based API which allows access to all functions and features of the database engine.
Here's the link to the documentation I used: https://www.arangodb.com/docs/3.8/http/index.html
(I'm using version 3.8 because after that the type of replication I needed was no longer part of the community edition).
Setting up a replication requires just two steps:
PUT request to the /_db/yourDBname/_api/replication/applier-config with a JSON payload:
{
"endpoint":"tcp://serverIP:8529",
"database":"yourDBname",
"username":"root",
"password":"password",
"autoResync": true,
"autostart":true
}
And another PUT request to get the replication actually started, to /_db/yourDBname/_api/replication/applier-start . This one doesn't need any payload
And to see how things are going you can do a GET request to /_db/yourDBname/_api/replication/applier-state
All these requests need a JWT token that you can get with a POST request to /_open/auth with a payload of:
{
"username": "user",
"password": "passwd"
}
The token you receive will need to be included in the HTTP header as a bearer token. Pretty simple.
I am trying to use QuotaGuard Static IPs to host a Next.js application. The Next API routes are running Prisma which, in turn is making direct db requests to a protected Microsoft SQL Server.
The client has whitelisted my IP for local development and the app works fine. But on Heroku you can't get a static IP without the QuotaGard.
I don't believe I have set up the QuotaGuard correctly or the server.js file. The rest of the app is working fine. Here are those files:
Expected Behavior:
The server proxies its url to one provided by the QuotaGuard
The MS Sql Server can whitelist the IP
Next.js server.js uses the 'http-proxy-middleware' to proxy requests
Actual Behavior:
The app homepage just shows 'this is a proxy server'
The QuotaGuard dashboard does not show any requests
The prisma client cannot connect (connection refused)
// server.js
// BASICALLY A COMBO OF THESE TWO OPTIONS:
// - https://quotaguard.freshdesk.com/support/solutions/articles/5000013744-getting-started-with-node-js-standard-http-library-quotaguard
// - https://medium.com/bb-tutorials-and-thoughts/next-js-how-to-proxy-to-backend-server-987174737331
const express = require('express')
const { parse } = require('url')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
// proxy middleware options
const options = {
target: process.env.QUOTAGUARDSTATIC_URL, // target host
changeOrigin: true, // needed for virtual hosted sites
ws: true, // proxy websockets
}
app.prepare()
.then(() => {
const server = express()
if (!dev) {
server.use('*', createProxyMiddleware({ ...options }))
}
server.all('*', (req, res) => {
const parsedUrl = parse(req.url, true)
return handle(req, res, parsedUrl)
})
server.listen(process.env.PORT, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${process.env.PORT}`)
})
})
.catch((err) => {
console.log('Error:::::', err)
})
You can see the live app at https://planes-planner-staging.herokuapp.com/
In this case, based on what you shared, you are close, but you need to go with the SOCKS proxy using the QuotaGuard QGTunnel software.
Steps to set that up are :
Download QGTunnel into the root of your project
curl https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz | tar xz
Log in to the QuotaGuard dashboard and setup the tunnel
Since you are using Heroku, you can use the Heroku CLI to log into the dashboard with the following command:
heroku addons:open quotaguardstatic
Or if you prefer, you can login from the Heroku dashboard by clicking on QuotaGuard Static on the resources tab of your application.
Once you are logged into the dashboard, in the top right menu, go to Setup (Gear Icon), click on QGTunnel Configuration, then Create Tunnel.
Remote Destination: tcp://hostname.for.your.server.com:1433
Local Port: 1433
Transparent: true
Encrypted: false
This setup assumes that the remote mssql server is located at hostname.for.your.server.com and is listening on port 1433. This is usually the default port.
The Local Port is the port number that QGTunnel will listen on.
In this example we set it to 5432, but if you have another process using 1433, you may have to change it (ie: 1434).
Transparent mode allows QGTunnel to override the DNS for hostname.for.your.server.com to 127.0.0.1, which redirects traffic to the QGTunnel software. This means you can connect to either hostname.for.your.server.com or 127.0.0.1 to connect through the tunnel.
Encrypted mode can be used to encrypt data end-to-end, but if your protocol is already encrypted then you don't need to spend time setting it up.
Change your code to connect through the tunnel
With transparent mode and matching Local and Remote ports you should not need to change your code. You can also connect to 127.0.0.1:1433.
Without transparent mode, you will want to connect to 127.0.0.1:1433.
Change your startup code
Change the code that starts up your application. In Heroku, this is done with a Procfile. Basically you just need to prepend your startup code with "bin/qgtunnel".
So for a Procfile that was previously:
web: your-application your arguments
you would now want:
web: bin/qgtunnel your-application your arguments
If you do not have a Procfile, then Heroku is using a default setup in place of the Procfile based on the framework or language you are using. You can usually find this information on the Overview tab of the application in Heroku's dashboard. It is usually under the heading "Dyno information".
Commit and push your code
Be sure that the file bin/qgtunnel is added to your repository.
If you are using transparent mode, be sure that vendor/nss_wrapper/libnss_wrapper.so is also added to your repository.
If you are not using transparent mode, you will want to set the environment variable QGTUNNEL_DNSMODE to DISABLED to avoid seeing an error message in your logs.
If you have problems...
Enable the environment variable QGTUNNEL_DEBUG=true and then restart your application while watching the logs.
VERY IMPORTANT
After you get everything working
Download your QGTunnel configuration from the dashboard as a .qgtunnel file and put that in the root of your project. This prevents your project from relying on the QG website during startup.
Alternatively you can put the contents of the downloaded configuration file in a QGTUNNEL_CONFIG environment variable.
To eliminate cors OPTIONS requests I want to proxy API calls through the Next.JS server. I've added this configuration change to my next.config.js file:
const withImages = require("next-images");
const { environment } = require("./environments/environment");
module.exports = withImages({
rewrites: async () => [
{ source: "/proxy/api/:match*", destination: `${environment.apiUrl}/:match*` },
],
});
I'm running next version 10.2.3 (latest at time of posting).
Calls to the back-end are performed through fetch within React components. In the browser dev tools I can see that the HTTP request is being performed. A request is sent out to "http://localhost:4200/proxy/api/user/me". It hits the Next server. But after that the Next server does not hit the API server. It responds immediately with a 404. It seems that it hasn't recognized the "rewrites" configuration at all.
This was an issue with an outdated version of nx
I am starting a new project, Nuxt.js for the frontend and Laravel for the backend.
How can I connect the two?
I have installed a new Nuxt project using create-nuxt-app, and a new laravel project.
As far as I have searched, I figured I need some kind of environment variables.
In my nuxt project, I have added the dotenv package and placed a new .env file in the root of the nuxt project.
And added CORS to my laravel project, as I have been getting an error.
The variables inside are indeed accessible from the project, and im using them
like this:
APP_NAME=TestProjectName
API_URL=http://127.0.0.1:8000
And accessing it like this:
process.env.APP_NAME etc'
To make HTTP calls, I am using the official Axios module of nuxt.js, and to test it i used it in one of the components that came by default.
The backend:
Route::get('/', function () {
return "Hello from Laravel API";
});
and from inside the component:
console.log(process.env.API_URL)//Gives 127.0.0.1:8000
//But this gives undefined
this.$axios.$get(process.env.API_URL).then((response) => {
console.log(response);
});
}
What am I doing wrong here?
I have tried to describe my setup and problem as best as I can. If I overlooked something, please tell me and I will update my question. Thanks.
Taking for granted that visiting https://127.0.0.1:8000/ in your browser you get the expected response, lets see what might be wrong in the front end:
First you should make sure that axios module is initialized correctly. Your nuxt.config.js file should include the following
//inclusion of module
modules: [
'#nuxtjs/axios',
<other modules>,
],
//configuration of module
axios: {
baseURL: process.env.API_URL,
},
Keep in mind that depending on the component's lifecycle, your axios request may be occurring in the client side (after server side rendering), where the address 127.0.0.1 might be invalid. I would suggest that you avoid using 127.0.0.1 or localhost when defining api_uris, and prefer using your local network ip for local testing.
After configuring the axios module as above, you can make requests in your components using just relative api uris:
this.$axios.$get('/').then(response => {
console.log(response)
}).catch(err => {
console.error(err)
})
While testing if this works it is very helpful to open your browser's dev tools > network tab and check the state of the request. If you still don't get the response, the odds are that you'll have more info either from the catch section, or the request status from the dev tools.
Keep us updated!
Nuxt has a routing file stucture to make it easy to set up server side rendering but also to help with maintainability too. This can cause Laravel and Nuxt to fight over the routing, you will need to configure this to get it working correctly.
I'd suggest you use Laravel-Nuxt as a lot of these small problems are solved for you.
https://github.com/cretueusebiu/laravel-nuxt
I am working on an app using a React frontend and Express backend, with GraphQL setup through Apollo (I am following and modifying tutorial https://www.youtube.com/playlist?list=PLN3n1USn4xlkdRlq3VZ1sT6SGW0-yajjL)
I am currently attempting deployment, and am doing so with Heroku. Everything functions perfectly on my local machine before deployment and on Heroku in Google Chrome. However, I get the aforementioned errors in Safari and Firefox, respectively. Wondering why this is happening in these browsers and how to fix.
I have spent about 10 hrs doing research on this. Things I tried that made no difference:
I tried adding CORS to my express backend
I tried serving the graphql endpoint as HTTPS
Moving app.use(express.static) in main app.js server file
I couldn't find many other things to try. Everywhere I looked seemed to say that CORS fixed the problem, but mine persists.
Github link: https://github.com/LucaProvencal/thedrumroom
Live Heroku App: https://powerful-shore-83650.herokuapp.com/
App.js (express backend):
const cors = require('cors')
// const fs = require('fs')
// const https = require('https')
// const http = require('http')
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(cors('*')); //NEXT TRY app.use(cors('/login')) etc...
app.use(cors('/*'));
app.use(cors('/'));
app.use(cors('/register'));
app.use(cors('/login'));
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
server.applyMiddleware({ app }); // app is from the existing express app. allows apollo server to run on same listen command as app
const portVar = (process.env.PORT || 3001) // portVar cuz idk if it will screw with down low here im tired of dis
models.sequelize.sync(/*{ force: true }*/).then(() => { // syncs sequelize models to postgres, then since async call starts the server after
app.listen({ port: portVar }, () =>
console.log(`🚀 ApolloServer ready at http://localhost:3001${server.graphqlPath}`)
)
app.on('error', onError);
app.on('listening', onListening);
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Full file is on Github, I tried to post only relevant parts above.
The expected result is that it works in all browsers. It seems from my research that since Heroku serves on HTTPS, Safari and Firefox do not allow requests to HTTP (which is where the graphql server is located, http://localhost:3001/graphql'). When I tried serving Apollo on HTTPS, Heroku just crashed, giving me H13 and 503 errors.
Thanks for any help...
This may also happen during local development when running the front end using HTTPS, but the back end using HTTP.
This is because CORS treats two URLs as having the same origin "only when the scheme, host, and port all match". Matching scheme means matching protocols e.g. both http, or both https.
One solution for local development is to proxy the back end using a tool such as ngrok.
Suppose the front end uses an environment variable which indicates the back end's URL:
BACK_END_API_URL=http://localhost:3005. Then do the following.
Install ngrok
Identify what port the back end is running on e.g. 3005
Run ngrok http 3005 at the command line, which will establish both http and https endpoints. Both will ultimately proxy the requests to the same back end endpoint: http://localhost:3005
After running ngrok it will display the http and https endpoints you can use. Put the one that matches the front end protocol you're using (e.g. https) into your front end environment variable that indicates the back end's URL e.g.
BACK_END_API_URL=https://1234asdf5678ghjk.ngrok.io
Was going to delete this because it is such a silly problem but maybe it will help someone in the future:
I simply replaced all of my 'http://localhost:PORT' endpoints in development with '/graphql'. I assumed that localhost meant local the machine running the code. But an app running on Heroku does not point to localhost. The express server is served on the url (https://powerful-shore-83650.herokuapp.com/) in our case...
At any rate I am so glad I came to a solution. I have a full stack app deployed and connected to a db. Hopefully this post can save someone lots of time.