如何解决使用fs.writeFile写入文本文件后停止执行
let app = express();
app.use(cors());
app.get('/callback',function (req,res) {
// your application requests refresh and access tokens
// after checking the state parameter
var code = req.query.code || null;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',form: {
code: code,redirect_uri: redirectUri,grant_type: 'authorization_code'
},headers: {
'Authorization': 'Basic ' + (new Buffer(clientId + ':' + clientSecret).toString('base64'))
},json: true
};
request.post(authOptions,function (error,response,body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,refresh_token = body.refresh_token;
fs.writeFile('test.txt','HELLO',function (err) {
if (err) return console.log(err);
console.log('Hello World > helloworld.txt');
});
}
}
)
});
console.log('Listening on 8888');
app.listen(8888);
该路由用作对Spotify Web API的请求的回调,因此我可以获得访问令牌。
Spotify然后重定向到上面的回调函数,您可以通过查看“ redirect_uri”在URI中看到它。
如果您需要有关Spotify授权流程的更多信息,请参见here。
这是我用来向Spotify验证我的应用程序的URI。
在我提出的请求中,CLIENT_ID替换为我的真实CLIENT_ID
我的问题出在文件写入部分:
fs.writeFile('test.txt',function (err) {
if (err) return console.log(err);
console.log('Hello World > helloworld.txt');
});
当Spotify调用回调路由时,我在文本文件中写入了字符串“ HELLO”,因此该文件可以正常工作。
但是,即使它已经完成了字符串的写入,Chrome页面仍在运行并“挂起”在服务器上。它运行了几分钟,然后通过说该页面未发送任何数据而崩溃。为什么?
我看过this page,谈论使用writeFile和writeFileAsync写入文本文件的方法,但同时使用它们并不能解决我的问题。
编辑:我真的不想停止Express流程!我只希望能够处理另一个请求:)
有什么主意吗?在此先感谢:)
解决方法
您没有从路线返回任何东西,请尝试添加res.send({})
在获取路线中,您没有发送响应,无论写文件成功与否,都必须发送响应。
将以下代码发布添加到文件中(以及在错误情况下)
res.send({YOUR_CHOICE_RESPONSE_DATA})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。