Friday 28 April 2017

socket.io emit confict with res.json of express?

chrome extension did ajax post:

$.ajax({
  type: 'POST',
  url: 'http://127.0.0.1:8000/api/v1',
  data: paras,
  success: function(d) {
    console.log(JSON.stringify(d));
    alert('OK');
  },
  error: function(e) {
    alert('Error');
  }
});

Express server accepting this post and will return json and send msg on socket.io, my app.js:

const express = require('express'),
      morgan = require('morgan'),
      bodyParser = require('body-parser'),
      path = require('path'),
      mongoose = require('mongoose'),
      app = express(),
      config = require('./config'),
      Note = require('./models/note'),
      server = require('http').createServer(app),
      io = require('socket.io')(server);

mongoose.connect('mongodb://'+config.db.host+'/'+config.db.name);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));

app.use(function(req, res, next) {
  const allowedOrigins = [
    'http://127.0.0.1:8000',
    'http://localhost:8000',
    'http://127.0.0.1:3000',
    'http://localhost:3000'
  ];
  const origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  //res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Credentials', true);
  res.io = io;
  next();
});

// Always return the main index.html
app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});

app.post('/api/v1', (req, res) => {
  let apple = new Apple();

  apple.save( err => {
    if(err) {
      res.send([]);
    }
    res.io.emit('Test1', apple );
    res.json(apple);
  });
});

My index.js

'use strict';

const app = require('./app'),
      // server = http.createServer(app),
      PORT = process.env.PORT || 8000;

app.listen(PORT, () => {
  console.log(`REST API running on ${PORT}!`);
});

The client listening to the express server and sending back msg on socket.io

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
    <script>
      var socket = io('http://127.0.0.1:8000');
      socket.on('Test1', function (data) {
        console.log(data);
        socket.emit('hi', { my: 'data1' });
      });
      socket.on('Test2', function (data) {
        console.log(data);
        socket.emit('hi', { my: 'data2' });
      });

</script>
  </body>
</html>

But there are two issues: 1, res.json(...) will fail. and alert of Error will be popped out. If res.json(...) commented, alert of OK will be popped out.

2, on the server side, msg of { my: 'data1' } can not be received.

Any idea? Thanks



via BAE

No comments:

Post a Comment