下面是一个Webshop服务器的精简部分,有两个API:./login
用于登录,./products
用于展示产品.只有在成功登录后才能显示产品.
我使用的是带有Node.js的TypeScrip和启用了会话管理的Express.下面的代码还try 通过向API发送fetch()
个请求来测试服务器.注意:我从within个Node.js发送了fetch()
个请求,而不是从浏览器.下面的代码生成以下输出:
Login session ID: um2RykooJCer7Oy7YmJQs7s9ge3mZWL1
Products session ID: uAk03ochUM56rzJjPvbiRnFuPG8CUqTB
Products response: Error: Not logged in
可以看出,会话ID是不同的,这就是它无法显示产品的原因.当我让代码保持运行并在浏览器中手动键入API调用时:
http://localhost:3000/login
http://localhost:3000/products
然后代码就可以正常工作了,浏览器显示"Login OK",然后显示"Apple, Orange, Pear",两者都具有相同的会话ID.
所以问题是:如何让服务器测试在Node.js中正确地使用fetch()
,就像从浏览器调用时一样?是否有一些选项可以给fetch()
个请求或Express?我还没有找到.
附加问题:它也可以与NPM包的 node 获取一起工作吗?我使用它是因为Node.js的内置fetch()
在其他地方给出了错误.
PS我使用的是最新版本的Node.js(v21.5)、Express、Express-Session和Node-Fetch.
import Express from "express";
import Session from "express-session";
// Uncomment this to use the node-fetch module, but gives the same result:
// import fetch from "node-fetch";
declare module 'express-session' {
interface SessionData
{
loggedIn: boolean;
}
}
class App
{
express = Express();
start()
{
let session = Session( { secret: "my-secret", /* options? */ } );
this.express.use( session );
this.express.get( "/login", ( request, response ) => this.onLoginRequest( request, response ) );
this.express.get( "/products", ( request, response ) => this.onProductsRequest( request, response ) );
this.express.listen( 3000, () => this.requestLogin() );
}
// =================================== Login
requestLogin()
{
fetch( 'http://localhost:3000/login', { /* options? */ } )
.then( result => this.showProducts() );
}
onLoginRequest( request: Express.Request, response: Express.Response )
{
console.log( "Login session ID: " + request.session.id );
request.session.loggedIn = true;
response.send( "Login OK" );
}
// =================================== Products
showProducts()
{
fetch( 'http://localhost:3000/products', { /* options? */ } )
.then( result => this.onProducts( result ) );
}
onProductsRequest( request: Express.Request, response: Express.Response )
{
console.log( "Products session ID: " + request.session.id );
if( !request.session.loggedIn )
response.send( "Error: Not logged in" );
else
response.send( "Apple, Orange, Pear" );
}
onProducts( result: any )
{
result.text()
.then( ( text: string ) => console.log( "Products response: " + text ) );
}
}
( new App() ).start();