Ajax post response from express js keeps throwing error

后端 未结 2 1752
再見小時候
再見小時候 2021-01-16 10:27

I am having a real hard time standing up bidirectional data transfer from a html page to my node.js application and then back to the html page.

I\'m pretty sure I\'m

相关标签:
2条回答
  • 2021-01-16 10:49

    Your code is perfectly fine, but you're almost certainly running into a cross-domain AJAX request issue. You might be opening this HTML file on the local filesystem and making requests that way, which is what is causing this problem.

    To fix it, add app.use(express.static('public')); like so:

    var express = require('/usr/lib/node_modules/express');
    var app = express();
    
    app.use(function(err, req, res, next){
      console.error(err.stack);
      res.send(500, 'Something broke!');
    });
    
    app.use(express.bodyParser());
    app.use(express.static('public'));
    
    app.post('/namegame', function(req, res)
        {
            console.log('Got request name: ' + req.body.name);
            setTimeout(function() 
            { 
                var newName = "New Name-O";
                res.send({name: newName});
            }, 2000);
        }
    );
    
    app.listen(8088, function() { console.log("Server is up and running");  });
    

    and then place your html file in the 'public' folder. Once you launch your server, you can visit http://127.0.0.1:8088/file.html and your code will run fine.

    0 讨论(0)
  • 2021-01-16 10:59

    In my case adding this to the app.js works.

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    

    https://enable-cors.org/server_expressjs.html

    0 讨论(0)
提交回复
热议问题