LINE API回调页面无法输出token_response,求渲染解决方案
Hey there, let's break down why you can't get the token_response to show up on your callback page and fix it step by step.
First, Spot the Critical Configuration Mismatch
Looking at your code, the callback_url in your line_login setup is set to /m.html, but your actual callback route is /callbackurl. LINE needs the full, exact URL of your callback endpoint to send the authorization response to—this mismatch is probably why your callback handler isn't even firing, let alone rendering content.
Step 1: Correct the Callback URL Configuration
Update your line_login initialization to use the full callback URL (match your route and server address):
const login = new line_login({ channel_id: 118, // Replace with your real channel ID channel_secret: "6907", // Replace with your real channel secret callback_url: "http://localhost:5000/callbackurl", // Use your actual domain for production (must be HTTPS!) scope: "openid profile", prompt: "consent", bot_prompt: "normal" });
Note: For production, LINE requires HTTPS for callback URLs—make sure your deployed server uses HTTPS.
Step 2: Create a Callback Template to Render the Response
Since you're already using EJS as your template engine, let's make a dedicated page to display the token_response. Create a new file at views/pages/callback.ejs with this content:
<!DOCTYPE html> <html> <head> <title>LINE Login Success</title> <link rel="stylesheet" href="/css/style.css"> <!-- Link your CSS if needed --> </head> <body> <div class="container"> <h1>Login Successful!</h1> <h3>Authorization Token Details:</h3> <pre><%= JSON.stringify(tokenResponse, null, 2) %></pre> </div> </body> </html>
The <pre> tag will format the JSON response nicely for readability.
Step 3: Update the Callback Handler to Render the Template
Instead of using res.send() (which returns raw JSON), use res.render() to load your new template and pass the token_response as data:
app.use("/callbackurl", login.callback((req, res, next, token_response) => { // Success callback: render the callback page with token data res.render('pages/callback', { tokenResponse: token_response }); },(req, res, next, error) => { // Failure callback: render an error page (create this template too if needed) res.status(400).render('pages/error', { error: error }); }));
Why This Works
- Fixing the
callback_urlensures LINE sends the authorization response to your correct/callbackurlroute, so your handler actually runs. - Using
res.render()with EJS lets you inject thetoken_responseinto an HTML page, instead of just sending raw JSON to the browser.
Quick Troubleshooting Tips
- Check your server logs to confirm the
/callbackurlroute is receiving requests from LINE. - Make sure your
viewsdirectory structure matches (e.g.,views/pages/callback.ejsexists). - For production, replace
http://localhost:5000/callbackurlwith your actual HTTPS domain (e.g.,https://your-app.com/callbackurl).
内容的提问来源于stack exchange,提问作者John Wick

