Actioncable works locally but not after deploying to Heroku - Rails & React - ruby-on-rails

I am using actioncable for a chat feature. It works perfectly when I test locally, but when I deploy to Heroku I get this error:
'WebSocket connection to 'wss://dg-automotive-portal-
rails.herokuapp.com/cable' failed: Error during WebSocket handshake: Unexpected response code: 404'
production.rb:
config.action_cable.url = 'wss://dg-automotive-portal-
rails.herokuapp.com/cable'
config.action_cable.allowed_request_origins = [
'https://dg-automotive-portal.herokuapp.com/', 'http://dg-
automotive-portal.herokuapp.com/' ]
cable.yml:
production:
adapter: redis
url:redis:MYURL
routes.rb has
mount ActionCable.server => '/cable'
And I have the redis gem installed. Does anyone know why this doesn't work when I deploy?
Javascript code called on componentWillMount:
createSocket() {
let cable = Cable.createConsumer('wss://dg-automotive-portal-rails.herokuapp.com/cable')
this.chats = cable.subscriptions.create({
channel: 'ChatChannel'
}, {
connected: () => {
console.log("connected!")
},
received: (data) => {
this.setState({
chatLogs: [...this.state.chatLogs, data]
})
},
create: function(chatContent, datetime, currentUser) {
this.perform('create', {
content: chatContent,
time: datetime,
user_id: currentUser
})
}
})
}

Related

504 XOAUTH2 authentication mechanism not supported

Using Google OAUTH service to send an email using nodemailer. It works in the local environment (windows), but not in production (AlmaLinux OS).However, gave me an "504 XOAUTH2 authentication mechanism not supported" error in production environment.
Any suggestions would be greatly appreciated. Thanks
Code:
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: "test#gmail.com",
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRECT,
refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
accessToken: googleToken
},
tls: {
rejectUnauthorized: true
},
})
const mailData = {
from: "test#gmail.com",
to: emailDetails.to,
subject: emailDetails.subject,
// text: emailDetails.message,
html: `<div>${emailDetails.message}</div>
`
}
// console.log(JSON.stringify(mailData));
transporter.sendMail(mailData, function (err, info) {
if(err){
console.log(err)
res.send({status: 0, message:"Error occured", errors: [{code: "", message: err}]});
} else {
console.log(info)
res.send({status: 1, message:"successfully send an email", errors: []});
}
transporter.close();
})
}).catch(error => console.log(error));
][1]
Error message output here:
enter image description here

Why my Vercel serverless functions not working in production?

Hello I have a problem when I deploy my application in vercel, I am creating a function without server that brings me the data of a collection in mongodb, using mongoose. In local everything works fine but when I deploy the function it gives me this error:
504: GATEWAY_TIMEOUT
Code: FUNCTION_INVOCATION_TIMEOUT
ID: gru1 :: 594vg-1620811347355-66f311d5c992
I understand that the free plan of vercel allows you to create functions with a maximum of 10 seconds of waiting, is this why I get the error? Or it may be for one of these reasons: https://vercel.com/support/articles/why-does-my-serverless-function-work-locally-but-not-when-deployed
Serverless function:
import mongoose from "mongoose";
module.exports = function(req, res) {
const Schema = mongoose.Schema;
const inmuebleSchema = new Schema({
user_id: String, //{type: Schema.Types.ObjectId, ref: 'User'}
desc: String,
tipo_propiedad: { type: String, enum: ["casa", "quinta", "departamento"] },
amb: Number,
estado: { type: String, enum: ["venta", "alquiler"] },
banios: Number,
dorm: Number,
coch: Number,
direc: String,
precio: String,
images: { type: Array, default: [] },
uploadedDate: { type: Date, default: Date.now() }
});
const Inmueble = mongoose.model("inmueble", inmuebleSchema);
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
Inmueble.find()
.exec()
.then(inmuebles => res.json({ inmuebles }))
.catch(err => res.json({ status: "error" }));
})
.catch(err => {
res.status(500);
});
};
The problem was, I wasn't adding my site's IP to my cluster's whitelist.

Enable CORS for AngularJS application on YEOMAN

I am trying to redirect my application to a payment gateway using $http post method
below is the code:
$http.post("payment api",paymenttrans,
{headers: { 'content-type':'application/json; charset=utf-8',
'X-App-Token':payment token }})
.then(function (success){
//some code
},function (error){
//some code
});
grunt file is as below :
grunt.initConfig({
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',`enter code here`
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9000,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
}
})
I am getting an error stating that :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at Payment page. (Reason: missing token ‘content-type’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
Need help on this with Grunt configuration or server configuration
Web server : NGINX.
Application Server : Puma.
Language : Ruby on Rails.
I have tried solutions like https://gist.github.com/Vp3n/5340891 which didn't help my problem.

How do I fix this webpack deploy error on heroku?

When trying to deploy a react_on_rails app to heroku. I get a series of the following errors. Everything works fine locally, however when I try to deploy to heroku I get:
ERROR in ./app/bundles/appbundle/startup/MyApp.jsx
remote: Module not found: Error: Cannot resolve 'file' or 'directory' /tmp/build_5f0499a33a66627b6911c88bcf69f8ab/client/node_modules/react in /tmp/build_5f0499a33a66627b6911c88bcf69f8ab/client/app/bundles/appbundle/startup
The error seems straight forward, but I don't understand why it is not finding the files. It finds them perfectly fine on my local machine, so I don't understand what is wrong.
const webpack = require('webpack')
const path = require('path')
const glob = require('glob')
const devBuild = process.env.NODE_ENV !== 'production'
const nodeEnv = devBuild ? 'development' : 'production'
const config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill'
].concat(glob.sync('./app/bundles/**/startup/*')),
output: {
filename: 'webpack-bundle.js',
path: '../app/assets/webpack'
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv)
}
})
],
module: {
loaders: [
{
test: require.resolve('react'),
loader: 'imports?shim=es5-shim/es5-shim&sham=es5-shim/es5-sham'
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
module.exports = config
if (devBuild) {
console.log('Webpack dev build for Rails') // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map'
} else {
config.plugins.push(
new webpack.optimize.DedupePlugin()
)
console.log('Webpack production build for Rails') // eslint-disable-line no-console
}

Ember POST 405 (Not Allowed) w/ Rails API

I am getting a POST https://heroku_client_path.herokuapp.com/login 405 (Not Allowed) for an Ember.js app with a Rails api (both on heroku)
When processing a login or sign up. I feel the Request URL should be the heroku server path /login as I set my ADAPTER_URL heroku config var, and not the heroku client URL shown above.
I believe I have CORS setup correctly.
I am using Ember-CLI. I hand rolled the auth it is not Simple-Auth.
environment.js:
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client-rantly',
environment: environment,
baseURL: '/',
adapterURL: process.env.ADAPTER_URL,
locationType: 'auto',
EmberENV: {
FEATURES: {
}
},
};
if (environment === 'development') {
}
if (environment === 'production') {
}
return ENV;
};
adapters/application.js:
import DS from 'ember-data';
import ENV from '../config/environment';
export default DS.ActiveModelAdapter.extend({
host: ENV.adapterURL || ENV.ADAPTER_URL,
headers: function () {
return {
'auth_token': localStorage.getItem('authToken')
};
}.property('authToken')
});
brocfile.js
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var app = new EmberApp({
dotEnv: {
clientAllowedKeys: ['ADAPTER_URL']
}
});
module.exports = app.toTree();
controllers/application.js
import Ember from 'ember';
export default Ember.Controller.extend({
needs: ['search'],
isAuthenticated: false,
init: function() {
var authToken = localStorage.getItem('authToken');
if(authToken) {
this.isAuthenticated = true;
}
},
actions: {
login: function () {
var credentials = {
email: this.get('email'),
password: this.get('password')
};
this.set('errorMessage', null);
return Ember.$.post('login', credentials).then(function(response){
this.set('errorMessage', response.error);
if (response.auth_token) {
localStorage.setItem('authToken', response.auth_token);
localStorage.setItem('userId', response.user_id);
this.set('isAuthenticated', true);
location.reload();
}
}.bind(this));
},
}
});
cors rails side - config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module ServerRantly
class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths << Rails.root.join('lib')
config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
allow do
origins '*'
resource '/cors',
:headers => :any,
:methods => [:post],
:credentials => true,
:max_age => 0
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options, :head],
:max_age => 0
end
end
end
end
On this line:
adapterURL: process.env.ADAPTER_URL
Where is process.env.ADAPTER_URL defined?
It seems like you are on the right track with overriding host on the ActiveModelAdapter adapter to use your non-client URL.

Resources