Nextjs + expressjs + Azure Web App : two factor authentication with express ('fs' can't be used on client side)

落爺英雄遲暮 提交于 2019-12-11 17:27:27

问题


Stack : next.js/express.js/typescript/nodemon

I have a dependency on azure devops api which seems to be using 'fs' under the hood. So I can't use this library in any of the pages (including in getInitialProps). I created a custom route (call it "get_data") in express server which provides me with the data. I call this route in getInitialProps of the page that will render the data (call it data.tsx) .

The whole app is behind two factor authentication in azure web apps. when get_data call is made in getInitialProps, I get a 401. Note that the origin is the same for serving the page and the get_data api.

  1. Is there a way to pass current auth context when I make the get_data api call ?
  2. In the express api, the method currently looks like this :
server.get('/get_data', (_req, res) => {
  let ado = new azure_devops() // this uses the azure-devop-api package 
  ado.get_data().then((data) => {
    res.setHeader('Content-Type', 'application/json');
    res.json(data) // return data as json 
  })
});

Is there a way to merge the two (page and data serving) like the following (so I don't have to make extra api call with auth setup) ?

server.get('/data', (req, res) => { //note the change in route that serves the page data.tsx 
  const actualPage = '/data'; 
  let ado = new azure_devops() // this uses the azure-devop-api package 
  ado.get_data().then((data) => { 
    res.setHeader('Content-Type', 'application/json'); 
    res.write(data) // BUT this is where method returns instead i want to just add to the response body 
    app.render(req, res, actualPage); // THIS is not executed (so the page doesn't get rendered) 
  }) 
});

Appreciate any pointers.


回答1:


Got the answer from this question.

Still making the API request from getInitialProps. I was missing adding cookie from the context.

const res = await fetch('http://' + context.req.headers.host + '/get_data', {
    headers: {
      cookie: context.req.headers.cookie, // WAS MISSING THIS
    }
  });


来源:https://stackoverflow.com/questions/57979227/nextjs-expressjs-azure-web-app-two-factor-authentication-with-express-fs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!