我尝试部署Web应用程序。但是我在网站上使用聊天时遇到问题。在本地可以正常运行,但不能在线运行。当我尝试访问聊天时,我收到响应401“未授权”。我使用socket.io
这是代码:
Index.js
const express = require('express');
const bodyparser = require('body-parser');
const security = require('./middleware/security');
const userRouter = require('./routes/user');
const AnnonceRouter = require('./routes/annonce');
const securityRouter = require('./routes/security');
const commentRouter = require('./routes/comment');
const mailRouter = require('./routes/mail')
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
const app = express();
const cors = require('cors');
var chat = require('https').createServer(app)
var io = module.exports.io = require('socket.io').listen(chat)
const SocketManager = require('./SocketManager')
io.on('connection', SocketManager)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('../client/build')); // serve the static react app
app.use(cors());
app.use(bodyparser.json());
app.use(security.verifyToken);
app.use('/', securityRouter);
app.use('/annonce', AnnonceRouter);
app.use('/user', userRouter);
app.use('/comment', commentRouter);
app.use('/mail', mailRouter);
app.get(/^\/(?!api).*/, (req, res) => { // don't serve api routes to react app
res.sendFile(path.join(__dirname, '../client/build/index.html'));
})
console.log('Serving React App...');
};
app.listen(PORT, function () {
console.error(`Node ${isDev ? 'dev server' : 'cluster worker '+process.pid}: listening on port ${PORT}`);
});
我的layout.js的一部分
import React, { Component } from 'react';
import io from 'socket.io-client'
import { USER_CONNECTED, LOGOUT } from '../Events'
import LoginForm from './LoginForm'
import ChatContainer from './chats/ChatContainer'
const socketUrl = "https://teachonline.herokuapp.com"
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
socket:null,
user:null
};
}
componentWillMount() {
this.initSocket()
}
/*
* Connect to and initializes the socket.
*/
initSocket = ()=>{
const socket = io(socketUrl)
socket.on('connect', ()=>{
console.log("Chat Connected");
})
this.setState({socket})
}
当我尝试访问我的聊天记录时,这里是Heroku中的日志
2019-08-26T22:25:04.828537 + 00:00 app [web.1]:TypeError:无法读取未定义的属性'replace' 2019-08-26T22:25:04.828550 + 00:00 app [web.1]:在verifyToken(/app/server/middleware/security.js:13:29)
这是我的security.js
const verifyJWTToken = require('../libs/auth').verifyToken;
const access_routes = ["/login_check", "/user", "/mail/send", "/landing-page", "/security/login", "/chat","/socket.io"]
const verifyToken = (req, res, next) => {
if(access_routes.indexOf(req.path) > -1) {
next();
} else {
const auth = req.get('Authorization');
if(!auth || !auth.startsWith('Bearer ')) {
res.sendStatus(401);
}
verifyJWTToken(auth.replace("Bearer ", ""))
.then((decodedToken) => {
req.user = decodedToken;
next();
})
.catch((error) => res.status(400).send({
error: "JWT TOKEN invalid",
details: error
}));
}
}
module.exports = {
verifyToken
}
如果需要auth.js
const jwt = require('jsonwebtoken');
const JWT_SECRET = "MaBelleJonquille";
const createToken = function (user = {}) {
return jwt.sign({
payload: {
userName: user.user_name
}
}, JWT_SECRET, {
expiresIn: "7d",
algorithm: "HS256"
});
};
const verifyToken = function (token) {
return new Promise((resolve, reject) => jwt.verify(token, JWT_SECRET, (err, decodedToken) => {
if(err || !decodedToken) {
reject(err);
}
resolve(decodedToken);
}));
};
//fonction pour hasher le password rentré
module.exports = {
createToken,
verifyToken
}
请求示例
let myHeaders = new Headers();
myHeaders.append("Content-type", "application/json");
myHeaders.append("Authorization", "Bearer "+localStorage.getItem('tokenJWT'));
fetch (URL + localStorage.getItem('user_name'),
{
method:'GET',
mode: "cors",
headers : myHeaders
})
.then(response => response.json())
.then(data => {
data.user_skill.map(x => {
this.skill.push({label: x, value: x});
});
})
.catch(error => (error));
我尝试了几种在互联网上找到的东西,但没有一个对我有用,因此,如果您对我在做什么错有任何了解,我在听。
感谢阅读我