0

I would use Socket.IO . I have read the official documentation and tried to do the same thing so I create my server :

// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express = require("express"); // call express
var app = express();
var bodyParser = require("body-parser");

// define our app using express
var routerProj = require("./routes/ajoutProj");

var mongoose = require("mongoose");

mongoose.Promise = global.Promise;

mongoose.connect("mongodb://localhost:27017", {
  useMongoClient: true

  /* other options */
}); // connect to our database

mongoose.connection.on("error", function(error) {
  console.log("error", error);
});
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");

  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/api/proj", routerProj);

app.get("/", function(req, res) {
  res.sendFile(__dirname + "../src/index.html");
});
// Chargement de socket.io

// Quand un client se connecte, on le note dans la console
io.sockets.on("connection", function(socket) {
  console.log("User is coonected!");
});
var port = process.env.PORT || 8081; // set our port

// START THE SERVER
// =============================================================================
var server = app.listen(port);
var io = require("socket.io").listen(server);

My angular index.htlm file is in this path relatively to server.js : ../src/app/index.html

When I restart server and angular app, then open new window I don't have a message on the servers's console telling me that a user is connected knowing that angular is making calls to the server api

I don't know where is the problem

Update

I have added socket.IO on client side

import { Injectable } from "@angular/core";
import { NouveauProjet } from "./models/nouveau-projet";
import { HttpClient, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import * as io from "socket.io-client";

@Injectable()
export class AjoutprojService {
  apiURL = "http://127.0.0.1:8080/api/proj/projets";
  private socket = io("http://localhost:8081");

  constructor(private http: HttpClient) {}

  getAllProj(): Observable<NouveauProjet[]> {
    return this.http.get<NouveauProjet[]>(
      "http://127.0.0.1:8081/api/proj/projets"
    );
  }
  getProj(id): Observable<NouveauProjet[]> {
    return this.http.get<NouveauProjet[]>(
      "http://127.0.0.1:8081/api/proj/nouvProjs/${id}"
    );
  }
  addProj(nouveauProjet: NouveauProjet): Observable<any> {
    return this.http.post<NouveauProjet[]>(
      "http://127.0.0.1:8081/api/proj/projets",
      nouveauProjet
    );
  }
}
/*  private handleError ( response: HttpResponse): Observable<any> {
    let errorMessage= `${response.status} - ${response.statusText}`;
    return Observable.throw(errorMessage);
  }*/

Restarted server , client , no result

Update 2 after adding socket.on('event', function(evt){ console.log(evt); });I get those errors :

Failed to load http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2tXQXh: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2tXQXh 404 (Not Found)

If I set res.header("Access-Control-Allow-Origin", "*"); To res.header("Access-Control-Allow-Origin", "http://localhost:4200"); I get this error

Failed to load http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2uichH: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I notice a difference in the error . Here The value of the 'Access-Control-Allow-Credentials' header in the response is '' When I put localhost:8081 : The value of the 'Access-Control-Allow-Credentials' header in the response is 'localhost:8081'

6
  • Can you post the client code that you are using to attempt to connect to the server via ws://? Commented Jan 2, 2018 at 13:40
  • I haven't implemented yet a client side . I wanted to try first on server side. is it possible ? Commented Jan 2, 2018 at 13:47
  • Hi Hamza: it does not have to be fancy, but you will not get any "User is connected!" messages until you build a client that can initiate a connection with the server. see https://socket.io/docs/. You need a minimal client that include socket.io.js and the var socket = io('http://localhost:8081'); line, if you are running locally. Commented Jan 2, 2018 at 13:51
  • @thmsdnnr I added socket.io as you mentioned, I updated my post. I have a question, I have an important question : I would implement socket.io to make a data stream on my api. can I only use socket.IO for server side and leave client side ? Commented Jan 2, 2018 at 14:18
  • Hi Hamza, if you are getting no results with this code, I suggest adding socket.on('event', function(evt){ console.log(evt); }); to the client to log connection events — you should be able to see what's going wrong. Regarding streaming: I'd look at socket.io-stream. I'd advise getting a simple client-server connection going first and then proceeding from there. Commented Jan 2, 2018 at 14:32

1 Answer 1

1

Based on the error, I suspect the problem is that you are using a wildcard in your server's CORS response header:

res.header("Access-Control-Allow-Origin", "*");

Why is this a problem? From the docs:

When responding to a credentialed request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.

Here is a relevant StackOverflow answer:

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port.

Sign up to request clarification or add additional context in comments.

6 Comments

In my case should I specify front end domain or back end ?
It will be the origin of the request, so if it's from a client, it would be the front-end domain.
I posted the message that I get
It looks like the server is also missing this: res.header("Access-Control-Allow-Credentials","true"); I'd check out this mdn article on CORS. These aren't socket.io issues, so it'd be worth it to make sure you have things running the way you expect.
actually the only error that I get is GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2v0L4d 404 (Not Found)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.