代码之家  ›  专栏  ›  技术社区  ›  Hamza Haddad

安装插座。NodeJs服务器上的IO

  •  0
  • Hamza Haddad  · 技术社区  · 7 年前

    我会用插座。IO。我读过官方的 documentation 并尝试做同样的事情,所以我创建了我的服务器:

    // 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);
    

    我的角度指数。htlm文件位于相对于服务器的此路径中。js:/src/app/index。html

    当我重新启动服务器和angular应用程序,然后打开新窗口时,服务器控制台上没有消息告诉我用户已连接,知道angular正在调用服务器api

    我不知道问题出在哪里

    使现代化

    我添加了套接字。客户端IO

    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);
      }*/
    

    已重新启动服务器、客户端,无结果

    更新2 添加后 socket.on('event', function(evt){ console.log(evt); }); 我发现这些错误:

    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)
    

    如果我设置 res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "http://localhost:4200"); 我得到这个错误

    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.
    

    我注意到错误的不同。在这里 The value of the 'Access-Control-Allow-Credentials' header in the response is '' 当我放置localhost:8081时: The value of the 'Access-Control-Allow-Credentials' header in the response is 'localhost:8081'

    1 回复  |  直到 4 年前
        1
  •  1
  •   thmsdnnr    7 年前

    根据错误,我怀疑问题在于您在服务器的CORS响应标头中使用了通配符:

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

    为什么这是一个问题? From the docs :

    响应认证请求时,服务器必须在Access Control Allow origin标头的值中指定原点,而不是指定“*”通配符。

    这是一个 relevant StackOverflow answer :

    这是安全的一部分,你不能这样做。如果要允许凭据,则访问控制允许源站不能使用*。您必须指定确切的协议+域+端口。