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));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器