gpt4 book ai didi

javascript - 在 NodeJs 服务器上安装 Socket.IO

转载 作者:行者123 更新时间:2023-12-03 02:47:02 25 4
gpt4 key购买 nike

我会使用 Socket.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);

我的 Angular index.htlm 文件相对于 server.js 位于此路径中:../src/app/index.html

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

不知道问题出在哪里

更新

我在客户端添加了socket.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.

我注意到错误有所不同。这里响应中“Access-Control-Allow-Credentials” header 的值为“”当我输入 localhost:8081 时: 响应中“Access-Control-Allow-Credentials” header 的值为“localhost:8081”

最佳答案

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

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

为什么这是一个问题? 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.

这是一个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.

关于javascript - 在 NodeJs 服务器上安装 Socket.IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48061994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com