我有一个用TypeScrip编写的工作客户端和一个用c#编写的遗留Web服务器.我正在try 将C#代码转换为nodes.js/express.
客户端获取函数:
export async function myFetch(url : String, data : Object | null) {
const bodyData = JSON.stringify(data);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: bodyData
}
const fullUrl = serviceBase() + url;
let res;
try {
if (data==null)
res = await fetch(fullUrl);
else
res = await fetch(fullUrl, options);
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
return await res.json();
}
catch (error : any) {
AlertError('Web error',error)
}
}
这是一个服务器端点的接口(在C#中):
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/GetRidesForDate", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[ServiceKnownType(typeof(List<Ride>))]
IEnumerable<Ride> GetRidesForDate(int date);
使用此选项,GetRidesForDate
将返回正确的结果.
在 node /快速try 中,我有:
const app = express ();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(port, () => {
console.log("Server Listening on PORT:", port);
});
app.get("/GetRidesForDate/:date", (request: any, response: { json: (arg0: any[]) => void; }) =>
{
console.log('getRidesForDate ' + request.params.date);
getRidesForDate(request,response);
})
但如果我用以下命令调用客户端FETCH
rides.value = await myFetch("GetRidesForDate",18800);
服务器代码永远不会到达console.log
,相反,我得到一个错误:
SyntaxError: Unexpected token '1', "#" is not valid JSON
at JSON.parse (<anonymous>)
这里的1
是提取数据的第一个数字.客户端发出400错误(错误请求).
如果我使用浏览器并转到http://localhost:3000/GetRidesForDate/18800
,NODE/Express服务器会正确响应.
app.get()
的参数应该是什么,才能使这与我的fetch
命令一起工作?