Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.3K
Visualizações
Receiving net::ERR_EMPTY_RESPONSE with Nodejs Post Request

I'm trying to make a post request in my Node app; however, I am getting the following error.

OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE

How to resolve this?

Here is my route:

var express = require('express');
var router = express.Router();
var Debate = require('../models/debate');
var mdb = require('mongodb').MongoClient,
  ObjectId = require('mongodb').ObjectID,
  assert = require('assert');
var api_version = '1';
var url = 'mongodb://localhost:27017/debate';

router.post('/'+api_version+'/postDebate', function(req, res, next) {
  var debate = new Debate(req.body);
  console.log(debate, "here is the debate");
  debate.save(function(err) {
    if (err) throw err;
    console.log('Debate saved successfully!');
  });
  res.json(debate);
});

module.exports = router;

And since I am invoking this route after onclick calling a function in my ejs file, here is my javascript file.

function postDebate() {
  var topic = document.getElementById('topic').value;
  var tags = document.getElementById('tags').value;
  var argument = document.getElementById('argument').value;

  var debateObject = {
    "topic": topic,
    "tags": tags,
    "argument": argument
  };
  console.log(topic, tags, argument);

  $.ajax({
    type: 'POST',
    data: JSON.stringify(debateObject),
    contentType: "application/json",
        //contentType: "application/x-www-form-urlencoded",
        dataType:'json',
        url: 'http://localhost:27017/post',                      
        success: function(data) {
          console.log(JSON.stringify(data), "This is the debateObject");                               
        },
        error: function(error) {
          console.log(error);
        }
      });
}

How do I resolve this error? What is the problem here?

OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need to add CORS headers on app level and you must to run res.end() on OPTIONS request

Then check your URL, you registered your module with some name so your URL should looks like /ROUTER_MODULE_NAME/1/postDebate but from your frontend you calling to http://localhost:27017/post

Here is minimal example which I checked and it works fine for me:

var express = require('express');
var router = express.Router();
var app = express();

app.use(function(req, res, next) {
    console.log('request', req.url, req.body, req.method);
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-token");
    if(req.method === 'OPTIONS') {
        res.end();
    }
    else {
        next();
    }
});

router.get('/hello', function(req, res, next) {
    res.end('hello world')
});

app.use('/router', router)

app.listen(8081)

//try in browser `$.get('http://127.0.0.1:8081/router/hello')`
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda