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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵