在提问之前,请注意,我已经尝试过许多来自堆栈溢出以及其他许多网站的建议。有很多建议,但大多数建议确实不能直接解决这个问题。
我的一个简单问题是,如何让我的web服务器(它是一个基于api的节点js表示)知道内部网应用程序中记录的windows用户id (来自我的react应用程序)?
到目前为止,我能够编写基于表达式的节点js服务器,它使用node库,并为我提供了windows用户id和组。这个API非常简单
var express = require('express');
var app = express();
var server = require('http').createServer(app);
let cors = require('cors')
app.use(cors())
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi');
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: true
});
nodeSSPIObj.authenticate(req, res, function(err){
res.finished || next();
});
});
app.get('*', function (req, res, next) {
res.json({msg: '************ Server reply by user ' + req.connection.user})
});
// Start server
var port = process.env.PORT || 3002;
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.get('env'));
});React App.js代码是
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
msg: "Not known",
localdata:"local status",
status:"not set",
};
}
componentDidMount()
{
fetch('http://192.168.7.179:3002/',{
method: 'GET', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
},
})
.then(response =>
{
this.state.status = response.status;
return response.text();
}
)
.then(msg =>
this.setState({ msg })
);
}
render() {
return (
<div className="App">
<div> LocalData is - {this.state.localdata}</div>
<div> Server data is - {this.state.msg} </div>
api call status is - { this.state.status }
</div>
);
}
}
export default App;在上面的代码中,如果从浏览器执行API调用,就会得到正确的答复。
http://192.168.7.179:3002/
{"msg":"************ Server reply by user IUYT\\user1"}但是,从
LocalData is - local status
Server data is -
api call status is - 401在F12窗口中
Failed to load resource: the server responded with a status of 401 (Unauthorized)请建议从react .调用所需的更改
发布于 2020-03-10 14:29:52
经过研究,昨天终于有了突破。所以我想回答我自己的问题。
在我的例子中有5点需要改变。
所以我的代码在这个例子中的全部变化是,
在服务器端
var corsOptions = {
origin: 'http://192.168.7.179:3001',
credentials: true,
authenticate: true,
authorization: true,
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))而不是
app.use(cors())在客户端添加“凭据:”作为要获取的参数。
变化
fetch('http://192.168.7.179:3002/',{
method: 'GET', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
}
})至
fetch('http://192.168.7.179:3002/',{
method: 'GET', // *GET, POST, PUT, DELETE, etc.
credentials: 'include'
})就是这样,第一次运行api,然后启动当你启动你的反应应用程序,你将得到一个提示窗口auth。填写您的域凭据,服务器将获取结果。
步骤1.在浏览器中查看服务器是否正在运行-> http://192.168.7.179:3002/
{“msg”:“*用户的服务器回复”}
LocalData是-本地状态
服务器数据-不知道
未设置api调用状态
但
浏览器中的http://192.168.7.179:3001/
LocalData是-本地状态
服务器数据为-{“msg”:“*用户的服务器回复”}
api调用状态为- 200。
https://stackoverflow.com/questions/60539828
复制相似问题