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

报告相同问题?

悬赏问题

  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格
  • ¥15 大家帮我看看为什么错了
  • ¥15 unity互动琴弦抖动效果
  • ¥15 做了个的二极管反向饱和电流测量电路,但是测试达不到效果
  • ¥15 nginx无证书访问https失败
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?