Estoy tratando de hacer una solicitud de publicación en mi aplicación Node; sin embargo, recibo el siguiente error.
OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE¿Cómo resolver esto?
Aquí está mi ruta:
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;Y dado que estoy invocando esta ruta después de hacer clic en llamar a una función en mi archivo ejs, aquí está mi archivo javascript.
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); } }); }¿Cómo resuelvo este error? ¿Cuál es el problema aquí?
OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSEDebe agregar encabezados CORS en el nivel de la app y debe ejecutar res.end () en la solicitud de OPCIONES
Luego verifique su URL, registró su módulo con algún nombre, por lo que su URL debería verse como /ROUTER_MODULE_NAME/1/postDebate pero desde su interfaz llama a http://localhost:27017/post
Aquí hay un ejemplo mínimo que verifiqué y funciona bien para mí:
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')`