Proxy error: Could not proxy request from Front End to Backend - mysql

I can't data insert in the database showing this error "Proxy error: Could not proxy request /auth/login from localhost:3000 to http://127.0.0.1:8000 (ECONNREFUSED).". I have installed "http-proxy-middleware" in my client folder...
setUpProxy.js
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/auth/register", { target: "http://127.0.0.1:8000/api" })
);
};

Related

aws rds proxy throws timeout error from nodejs12.x

I'm getting a connection timeout when I try to connect to mysql rds proxy. I'm followed this tutorial
This is my code
import mysql2 from 'mysql2';
import AWS from 'aws-sdk';
const getConnection = async () => {
const signer = new AWS.RDS.Signer({
username: 'my-user-name',
hostname: 'proxy-name.proxy-someid.us-east-1.rds.amazonaws.com',
port: 3306
});
console.info('Connecting to MySQL proxy via IAM authentication');
const rdsSignerAuth = () => () => {
console.info('CALL rdsSignerAuth');
return signer.getAuthToken({
username: 'my-user-name',
region: 'us-east-1',
hostname: 'proxy-name.proxy-someid.us-east-1.rds.amazonaws.com',
port: 3306
});
};
let connection;
try {
connection = await mysql2.createConnection({
host: 'proxy-name.proxy-someid.us-east-1.rds.amazonaws.com',
user: 'my-user-name',
database: 'database-name',
connectTimeout: 60000,
ssl: { rejectUnauthorized: false },
authPlugins: { mysql_clear_password: rdsSignerAuth },
});
console.info('Connected');
}
catch (e) {
console.error(`MySQL connection error: ${e}`);
throw e;
}
return connection;
};
const mysql2Impl = async () => {
const connection = await getConnection();
//console.info({ type: 'connection', connection });
const result = await connection.promise().query('select * from destiny;');
console.info({ type: 'result', result });
};
export async function testRdsProxy(event, context){
console.info(JSON.stringify({ event, context }));
await mysql2Impl();
return 200;
}
And this is the response
Error {
code: 'ETIMEDOUT',
errno: undefined,
message: 'connect ETIMEDOUT',
sqlState: undefined,
}
I already checked that my lambda function has a policy "rds-db:connect" to "*" resource. Besides, I checked that my proxy is in the same VPC and subnet that my rds db. The secret that holds the credentials to RDS is ok. What I am doing wrong?
The doc states that the RDS proxy cannot be accessed public, so your lambda function need to be in the same security group with the rds proxy.
Please aware that when you make your lambda into a vpc, your lambda may lost its ability to access internet.
Thank you.
You can connect RDS proxy even outside VPC by doing VPC peering from same or different account. I did it for one of the project
If you pass IAM certification
check the user-name(mysql user) has execute [INVOKE LAMBDA] permission
If IAM authentication fails
you should let the proxy setup wizard automatically create an IAM like below
Connectivity > IAM role > Create IAM role
                     > IAM authentication > Required

How to integrate React Native with mySQL

I'm new in React Native and I'm trying to integrate my app with mySQL database located inside my hosting provider (digitalocean.com).
I've managed to get the data through nodejs and express but it's actually getting the data where my problem is.
Here how it goes:
I created a routes.js and inserted the following:
Note: the following credentials are real but is for pure testing and i don't mind sharing.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '134.122.22.176',
user: 'yannb_9',
password: 'yannb_9',
database: 'tiomanGrow'
});
// Starting our app.
const app = express();
connection.connect((err) => {
if (err) {
console.log('Connection error message: ' + err.message);
return;
}
console.log('Connected!')
// Creating a GET route that returns data from the 'users' table.
app.get('/', function (req, res) {
// Connecting to the database.
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM farmers', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/farmers so you can see the data.');
});
Up until now everything's great! you can click on the http://localhost:3000/farmers and you'll see the data when you run the file.
Here's where I get stuck:
I was to display the data on my app and i have no idea how to possibly do that.
I did a few researches and saw a possible solution which didn't work. it actually gave me a "Network request failed"
import React from "react";
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import { HeaderImg } from '../components/HeaderImg';
import { Button } from '../components/Button';
export default class DB extends React.Component {
state = {
email: "",
password: "",
errorMessage: null
};
fetchData = async() => {
fetch('http://134.122.22.176:3000/farmers')
.then(response => response.json())
.then(users => console.dir(users))
.catch(error=> console.log(error))
}
render() {
return (
<View style={styles.container}>
<HeaderImg />
<View style={styles.errorMessage}>
{this.state.errorMessage && (
<Text style={styles.error}>{this.state.errorMessage}</Text>
)}
</View>
<Button
onPress={this.fetchData}
/>
</View>
);
}
}
const styles = StyleSheet.create({
});
Any suggestions?
The hostname for your MySQL database in your routes.js file is shown as 134.122.22.176. That's the database ip address. You cannot fetch from this IP address. MySQL databases do not respond to standard HTTP requests; they are not web servers.
Your Express app is running on localhost: http://localhost:3000/farmers - I am guessing you can surf to that URL in a web browser and see data, for example. If that Express app is running on your development computer, then you just need to find out the IP address (xx.xx.xx.xx) for that computer on your LAN, and use that in your fetch.
Starting from Android 9, google has decided to remove http client library from bootclasspath.
With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.
For brief overview of the changes, visit.
In order to connect with http client, you have to add this line in your AndroidManifest.xml file:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
After that you should be able to connect with HTTP clients with your android Pie device.

connection in channels.js returns undefined?

I'm trying to establish a real-time socket connection to my client
side via feathers channels. It works without any sort of
authentication. But if i add the following login action scoket is
throwing a weak map key error.
app.on('login', (authResult, { connection }) => {
console.log(connection) // returns undefined
....
})
This is the error I'm receiving
Unhandled Rejection at: Promise Promise { TypeError:
Invalid value used as weak map key
at WeakMap.set ()
app.on('login', (authResult, { connection }) => {
console.log("============>>", connection)
if (authResult && connection) {
app.channel('anonymous').leave(connection);
if (authResult.user && authResult.user['chanelName']) {
let channelName = authResult.user['chanelName'].toString();
channelName = channelName.substr(0, 5)
app.channel(`channel/${channelName}`).join(connection);
} else
app.channel('authenticated').join(connection)
}
});
The connection object is undefined, i think that causes the problem.
Anu suggestions?
Please provide the client side script.
According to fethers documentation connection can be undefined if there is no real-time connection, e.g. when logging in via REST.
You should authenticate your client.
Sample script
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const auth = require('#feathersjs/authentication-client');
const socket = io('http://localhost:3031');
const app = feathers();
// Setup the transport (Rest, Socket, etc.) here
app.configure(socketio(socket));
const options = {
header: 'Authorization', // the default authorization header for REST
prefix: '', // if set will add a prefix to the header value. for example if prefix was 'JWT' then the header would be 'Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOi...'
path: '/authentication', // the server-side authentication service path
jwtStrategy: 'jwt', // the name of the JWT authentication strategy
entity: 'user', // the entity you are authenticating (ie. a users)
service: 'users', // the service to look up the entity
cookie: 'feathers-jwt', // the name of the cookie to parse the JWT from when cookies are enabled server side
storageKey: 'feathers-jwt', // the key to store the accessToken in localstorage or AsyncStorage on React Native
storage: undefined // Passing a WebStorage-compatible object to enable automatic storage on the client.
}
app.configure(auth(options))
app.authenticate({
strategy: 'jwt',
accessToken: '<JWT TOKEN>'
}).then(() => {
console.log("Auth successfull")
const deviceService = app.service('myService');
deviceService.on('created', message => console.log('Created a message', message));
}).catch(e => {
console.error('Authentication error', e);
// Show login page
});
Hope this will help you.

x-devapi unable to connect to database in Google app-engine

I am deploying a simple nodejs server to App-engine which works well except for the database connection using the X-devapi. I am getting this error:
All routers failed.
Here is the code I use:
'use strict';
const express = require('express');
const mysqlx = require('#mysql/xdevapi');
const app = express();
app.get('/', (req, res) => {
const options = { user: 'user_name', password: '#pass',host: 'XX.XXX.XX.XXX'
/*Here I used Public IP address on the of the SQL instance*/,port: XXXX
/*I assigned port 8080 here*/, schema: 'db_name' };
(async function () {
let session;
try {
session = await mysqlx.getSession(options);
const collection = await session.getSchema(options.schema).createCollection('collection');
await collection.add({ name: 'foo' }).execute();
await collection.find().fields('name').execute(console.log); // { name: 'foo' }
} catch (err) {
//console.error(err.message);
res.status(200).send(err.message).end();//used code 200 in order to receive the error too
} finally {
session && session.close();
}
})();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
How can I solve this?
It turns out that Google cloud SQL tools still do not have the X devAPI enabled if you check response to my concern here and the feature request here

Apollo Server Subscriptions not working

I've made a GraphQL backend using Apollo Server, Sequelize (for the ORM), MySQL (DB) and Express (Web Server).
I have also added subscriptions, which the problem is there.
I can't even reach the WS endpoint using a websocket tester.
Can someone review my code and tell me what the problem is? I looked in the docs, other stackoverflow questions and I can't find any solution.
The code: https://github.com/seklyza/graphqlsubscriptions
Thanks for everyone
I think you have to make 2 Servers one for the app which uses the express server and one for the websocket. It could look like this.
GraphQL express server:
...
graphQLServer = express();
const GRAPHQL_PORT = 4000;
graphQLServer.use('/graphql', bodyParser.json(), graphqlExpress((request) => {
return {
schema: executableSchema,
};
}));
graphQLServer.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
graphQLServer.listen(GRAPHQL_PORT, () => {
console.log(`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`); // eslint-disable-line no-console
});
...
websocket server for subscriptions:
...
const WS_PORT = 8080;
const websocketServer = createServer((request, response) => {
response.writeHead(404);
response.end();
});
websocketServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console
`Websocket Server is now running on http://localhost:${WS_PORT}`
));
const subscriptionManager = new SubscriptionManager({
schema: executableSchema,
pubsub: pubsub,
setupFunctions: { /* your subscription channels */ },
});
subscriptionServer = new SubscriptionServer({
subscriptionManager: subscriptionManager
}, {
server: websocketServer,
path: '/',
});
...
And you need some sort of publication subscription service, we use pubSub. It is included in the server file and looks like this:
import {
PubSub
} from 'graphql-subscriptions';
const pubsub = new PubSub();
export {
pubsub
};
You can create some web socket server wrapper which implements start method which will be responsible for creating and running the WSServer, as well as it will create a SubscriptionServer with use of SubscriptionManager
// in subscription.js
import { PubSub, SubscriptionManager } from 'graphql-subscriptions';
const pubSub = new PubSub();
let subscriptionManagerOptions = {
schema: schema, // this is your graphql schema
setupFunctions: {
// here come your setup functions
},
pubSub: pubSub
};
const subscriptionManager = new SubscriptionManager(subscriptionManagerOptions);
export { pubSub, subscriptionManager };
After we have the subscriptionManager created, we can now implement the WSServer
import { createServer } from 'http';
import { SubscriptionServer } from 'subscription-transport-ws';
import { subscriptionManager } from './subscription';
const webSocketServerWrapper = {
start: function(port){
const webSocketServer = createServer((request, response) => {
response.writeHead(404);
response.end();
});
webSocketServer.listen(port, () => {
console.log('WSServer listening on port ' + port);
});
new SubscriptionServer({
subscriptionManager,
onSubscribe: (message, options, request) => {
return Promise.resolve(Object.assign({}, options, {}));
}
}, webSocketServer);
}
};
export default webSocketServerWrapper;
Now you can import the webSocketServerWrapper in the initialisation file like index.js and simply run webSocketServerWrapper.start(PORT);
Here, the second answer which I wrote, you can find a code responsible for creating example subscription and how it should be handled.