如何在Node JS中接收查询

时间:2019-06-05 15:34:45

标签: node.js

在节点中通过Spotify Web API授权后,我重定向到另一个页面,其网址为:http://localhost:8888/homepage#access_token= .... 所以我想在该页面上获取访问令牌并获取数据,但是当我使用req.query时,我收到一个空对象。有什么不对?如何获得该访问令牌?

request.post(authOptions, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      const access_token = body.access_token;
      const refresh_token = body.refresh_token;

      const options = {
        url: "https://api.spotify.com/v1/me",
        headers: { Authorization: `Bearer ${access_token}` },
        json: true
      };

      request.get(options, (error, response, body) => {
        console.log(body);
      });

      res.redirect(
        "/homepage#" +
          querystring.stringify({
            access_token: access_token,
            refresh_token: refresh_token
          })
      );
const express = require("express");
const router = express.Router();


router.get("/", (req, res) => {
  res.render("index/welcome");
});

router.get("/homepage", (req, res) => {
  res.render("index/homepage");
  console.log(req.query);
});

module.exports = router;


1 个答案:

答案 0 :(得分:0)

您是通过片段而不是查询参数传递令牌,不是吗?

const url = require('url'); 
res.redirect(url.format({
   pathname:"/homepage",
   query: {
      "access_token": access_token,
      "refresh_token": refresh_token
    }
 }));

使用片段仅用于客户端处理,永远不要到达服务器。