Express.js error: net connection closed

I have a Universal Javascript application deployed on Heroku.

In my setup, Express.js is loading my Vue.js app and proxying requests to https://localhost:3000/api.

However, when I try to send a simple POST request to an endpoint, the Chrome console displays:

OPTIONS https://localhost:3000/api net::ERR_CONNECTION_CLOSED

Below is the code snippet for my express server:

import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import path from 'path'
import mongoose from 'mongoose'
import routes from './routes'

mongoose.connect('mongodb://coolAddress');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log("mongoose connected")
})

const app = express()

const port = 3000

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())
app.use(express.static(path.resolve(__dirname, '../coolClient/dist')));

app.use('/api', routes)

app.all('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../coolClient/dist', 'index.html'));
})

app.listen(process.env.PORT || port, () => {
  console.log(`App listening on ${process.env.PORT || port}`)
})

I suspect that the issue might be related to SSL configuration. While searching online, I found suggestions pointing towards SSL as a possible cause, but no clear solution has been provided.

Does anyone have any insights or ideas on how to troubleshoot this?

Answer №1

After analyzing the feedback, there are a couple of key points to consider:

1) The term "localhost" refers to your own computer. In order for your client code to connect to it, you must have a server running on your machine that is able to handle your server-side code. It is essential to have a web-accessible domain name (such as the one provided by Heroku: app-name.herokuapp.com) to access your server-side code when it is hosted on Heroku or any other web host.

2) If you intend to use HTTPS, you will need to purchase and install an SSL certificate. This certificate will not be issued for the herokuapp domain, so you will also need to buy a domain name and configure it accordingly. Detailed instructions can be found in the Heroku documentation: https://devcenter.heroku.com/articles/ssl-endpoint

I hope this information proves helpful.

Answer №2

I successfully configured SSL requests on my Centos6.9 server with ease.

  • First, install Virtualmin on your server
  • Next, set up Let's Encrypt
  • Lastly, refer to the following steps

Make sure to include the code snippet below
var app = express();
before initializing any HTTP(S) mechanisms such as app.listen(port),

  var options = {
    key: fs.readFileSync('/home/yourdomain/ssl.key'),
    cert: fs.readFileSync('/home/domain/ssl.cert'),
  };

Important note: Remember to consider 'No Access Control Allow Origin' settings

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

At what point should you invoke db.close() while utilizing cursor.forEach()?

When working with .toArray(), it is common practice to include db.close() within the callback function. For example: db.collection('grades').find(query).toArray(function(err, docs) { if (err) throw err; console.dir(docs); db.close(); }); ...

Rows intersecting and stacking above one another

I designed a layout with some text and icons displayed in rows. While it appears properly on iOS, the rows overlap on Android. const criteriaList = [ { id: 0, title: 'Noor', checked: false }, { id: 1, title: 'Friends & Grades', ...

The functionality of anchor links created through ajax is not operating correctly

Issue: I am encountering a problem where I have a table filled via Ajax, containing local anchors. When an anchor is clicked, it should make a section visible and automatically scroll to it. This functionality works when manually filling the table, but not ...

Displaying HTML content within a Vue.js component property(Note: The

I'm a bit unsure about how to label this question, which may be why I can't seem to find any info on it online. Please correct me if I'm mistaken. Currently, I am utilizing the steps component from Element-ui <el-steps :active="active" ...

Issue with Collapse Feature on Bootstrap 3.x Navbar

The Bootstrap 3 Navbar expands properly in full screen and on a browser with a small width on a desktop PC and mobile browsers, but when using the Toggle navigation button, it doesn't slide down. I have tried to replicate the code from this example: h ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

Manipulating a React table: Customizing a row in the table

Below is the code snippet: const [data, setData] = useState([ {id: 1, name: 'paper', qty: 10}, {id: 2, name: 'bottle', qty: 10}, ]); const [isEditable, setEditable] = useState([]); useEffect(()=>{ data.map(each=>{ ...

Am I on track with this observation?

I am currently using the following service: getPosition(): Observable<Object> { return Observable.create(observer => { navigator.geolocation.watchPosition((pos: Position) => { observer.next(pos); observer.c ...

Utilizing AJAX and javascript for extracting information from websites through screen scraping

Is it possible to scrape a screen using AJAX and JavaScript? I'm interested in scraping the following link: I tried the technique mentioned on w3schools.com, but encountered an "access denied" message. Can anyone help me understand why this error is ...

Is it possible to utilize a for loop or a function to accomplish this task and create a concise and flexible solution for this particular array?

Hello there! I'm new to this platform and eager to learn. Any chance you could share some information with me and help me study a bit? var people = [ [1, 'Dimitri', 'Microsoft'], [2, 'Mike', 'Micro ...

Tips for organizing nested reactive data in VUE

It seems like a common issue arises when fetching a list from an API and then displaying it. You need to create a list of checkboxes for each item in the list, but the checked property needs to be handled carefully. <div v-for="item in items"> & ...

Guide to deploying a Node.js application

After setting up npm locally and installing Bower, Grunt, Polymer, and Yeoman, I find myself a little confused about what Node.js actually is. In the past, I would set up an Apache server, install phpMyAdmin, and start working on my project using PHP. Howe ...

Utilizing the map method to extract values from an array in JavaScript

I'm trying to modify this code so it returns individual values instead of arrays. The code compares IDs to check for matches and creates a priceList array with matching values. I'm wondering if there's a simpler way to achieve this, maybe us ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Are you facing an npm concurrently error while trying to simultaneously run both the frontend and backend applications?

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "server": "nodemon backend/server.js", "client": "npm start --prefix frontend" ...

Undefined value is encountered when passing props through the Context API in a REACT application

Exploring My Context API Provider File (Exp file) import react form 'react'; import {createContext} from "react"; export const ContextforFile = createContext(); export function ContextData(props){ let rdata=props.data return( &l ...

What is the best way to utilize the ajax factory method in order to establish a $scoped variable?

One issue I frequently encounter in my controllers is a repetitive piece of code: // Get first product from list Product.get_details( id ) .success(function ( data ) { // Setup product details $scope.active_product = data; }); To avoid this ...

Is there a way in jQuery Validation to apply a rule to the entire form rather than just individual elements within the form?

I am facing an issue with a form where each element has its own custom rules that work perfectly. However, the form cannot be submitted unless values are provided for at least one of its elements. It seems like this is a rule for the entire form rather th ...

Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing th ...

"Seeking a more flexible JSON parser that allows for greater

I am in need of passing various strings that are formatted as json to a json parser. The issue is that jQuery.parseJSON() and JSON.parse() strictly support only a specific json format: If a malformed JSON string is passed, an exception may be thrown. For ...