[英]Stop execution after writing to text file with fs.writeFile
我有以下 Node.JS(使用 Express 運行)代碼:
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 然后重定向到上面的回調 function,您可以通過查看“redirect_uri”在 URI 中看到它。
如果您需要有關 Spotify 授權流程的更多信息,請參閱此處。
這是我用來向 Spotify 驗證我的應用程序的 URI。
在我提出的請求中,CLIENT_ID 被我的真實 CLIENT_ID 替換
我的問題出在文件寫入部分:
fs.writeFile('test.txt', 'HELLO', function (err) {
if (err) return console.log(err);
console.log('Hello World > helloworld.txt');
});
當 Spotify 調用回調路由時,我的文本文件中寫入了字符串“HELLO”,因此文件寫入是有效的。
但即使它已經完成了字符串的寫入,Chrome 頁面仍在服務器上運行並“掛起”。 它運行了幾分鍾,然后說頁面沒有發送任何數據而崩潰。 為什么?
我看過這個頁面,討論了使用 writeFile 和 writeFileAsync 寫入文本文件的方法,但同時使用它們並沒有解決我的問題。
編輯:我真的不想停止 Express 進程:我只想能夠處理另一個請求 :)
任何想法? 提前致謝:)
您沒有從您的路線返回任何東西,請嘗試添加res.send({})
在您的獲取路線中,您沒有發送響應,無論寫入文件是否成功,您都必須發送響應。
添加以下代碼后寫入文件(以及在錯誤情況下)
res.send({YOUR_CHOICE_RESPONSE_DATA})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.