我创建了一个网站,前端使用 Angular2,后端使用 Node/Express。前端通过端口 4200 运行(npm run build 以便运行它),后端通过端口 4201(npm start)运行。
我有一个管理用户连接(登录名/密码)的 View ,它在本地主机上完美运行。基本上,我有一项服务将在表单提交时调用以获取指定的用户。问题是,当我在自己的服务器上尝试相同的操作时,我收到此错误:
选项http://[HostIP]:4201/auth/login
net::ERR_CONNECTION_REFUSED
我的服务器位于 1&1 云上,位于 debian7 环境中。防火墙似乎畅通无阻,端口似乎已打开。
你知道发生了什么吗?问题是来 self 的代码还是来自服务器?
服务器.js:
const express = require('express');
const app= express();
const bodyParser= require('body-parser');
let data = require('./dataPics');
const fakeUser = {dataFakeUser};
const secret = 'mySecret';
const jwt = require('jsonwebtoken');
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
next();
});
const auth = express.Router();
auth.post('/login', (req, res) => {
if(req.body){
const login = req.body.login.toLocaleLowerCase();
const password = req.body.password.toLocaleLowerCase();
if(login === fakeUser.login && password === fakeUser.password){
delete req.body.password;
//res.json({ success: true, data: req.body});
const token = jwt.sign({iss: 'http://localhost:4201', role: 'admin', user: req.body.login}, secret);
res.json({ success: true, token: token});
}
else{
res.json({ success: false, message: 'Identification Incorrecte'});
}
}
else{
res.json({ success: false, message: 'Merci de vous identifier'});
}
});
app.use('/auth', auth);
const port = 4201;
app.listen(port, '[HostIP]', () => {
console.log(`listening on port ${port}`);
});
服务.ts:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import * as jwtDecode from 'jwt-decode';
@Injectable()
export class LoginService {
// BASE_URL = 'http://localhost:4201/auth';
BASE_URL = 'http://[HostIP]:4201/auth';
constructor(private _http: Http) { }
login(formData){
return this._http.post(`${this.BASE_URL}/login`, formData)
.map(res => res.json());
}
userIsLoggedIn(){
return localStorage.getItem('jjw-data');
}
logOut(){
localStorage.removeItem('jjw-data');
}
decodeToken(token){
return jwtDecode(token);
}
}
谢谢:-)
最佳答案
localhost 是一个特殊的主机名,仅当从同一台计算机上托管的 Web 应用程序打开 URL 时才会运行,您可以尝试更改 http://localhost:4201使用您托管 Node 应用程序的计算机的公共(public)IP http://[publicIp]:4201
if(req.body){
const login = req.body.login.toLocaleLowerCase();
const password = req.body.password.toLocaleLowerCase();
if(login === fakeUser.login && password === fakeUser.password){
delete req.body.password;
//res.json({ success: true, data: req.body});
const token = jwt.sign({iss: 'http://localhost:4201', role: 'admin', user: req.body.login}, secret);
res.json({ success: true, token: token});
}
如果该解决方案不适合您,您可以尝试运行
netstat -antu
为了知道端口是否被不同的应用程序使用。
关于node.js - Angular 2 服务器 Express ERR_CONNECTION_REFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783970/