weixin_33690367 2016-10-11 00:57 采纳率: 0%
浏览 71

Ajax和ReactJS到NodeJS

I'm using webpack-dev-server while developing in ReactJS.
I also want to add a backend which will be written in NodeJS.
When I run the webpack-dev-server it binds to port 8080.
When I run node, it can't bind to the same port.
Therefore, I'm unable to perform $.ajax requests due to the SOP.
How do I get over this issue?

NodeJS:

const express = require('express');

const app = express();

app.get('/messages', function(req, res){
  res.send('hello world!');
});

let server = app.listen(8081, function() {
  const host = server.address().address;
  const port = server.address().port;

  console.log('Listening at http://%s:%s', host, port);
});

React/JS/Ajax:

$.getJSON('/messages', function(data) {
  this.setState({
    messages: data
  });
}.bind(this));

And I'm running webpack-dev-server without any parameters.

  • 写回答

2条回答 默认 最新

  • Lotus@ 2016-10-11 01:47
    关注

    Your app is on port 8080.

    Your server is on 8081.

    If you want to request from the server, you need to specify the port to the server. If not, it will request to the port your app is running to, which is 8080.

    $.getJSON('https://localhost:8081/messages', function(data) {
      this.setState({
        messages: data
      });
    }.bind(this));
    
    评论

报告相同问题?