我只是在网上找不到问题的答案,我希望有人可以帮助我。 我使用 Nodejs 和 Express 制作了一个 API(在 YouTube 和 Google 的帮助下)。 我能够在本地主机上执行一些获取和放置请求。 我还可以在另一台笔记本电脑上执行 GET 请求, 但当我在另一台笔记本电脑上尝试 PUT 请求时,它甚至无法到达服务器,并且它给了我一个被拒绝的承诺。
这里有一些代码可能会提供更多上下文: API(发送空字符串后应返回 418 代码):
const { getAllSoftware, updateMachines } = require('./services/db');
const express = require('express');
const cors = require('cors'); // Import CORS middleware
const app = express();
const PORT = 98;
// CORS configuration
const corsOptions = {
origin: ['http://192.168.1.99:94', 'http://localhost:94'], // Update with your client's domains
};
app.use(cors(corsOptions)); // Use CORS middleware
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
app.use(express.json());
app.put('/machines', async (req, res) => {
console.log(req.body);
if (req.body = {} || !req.body) {
res.status(418).send({message:'We need a json'})
return
}
res.status(200).send({
machine: `dit is je machine met je json ${req}`
})
});
来自不同笔记本电脑的 API 调用(
localStorageData
是一个空 JSON 字符串 {}
)
fetch('http://localhost:98/machines', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: JSON.stringify(localStorageData)
})
.then(response => {
// Handle the response here
console.log(response);
})
.catch(error => {
// Handle errors here
console.error('Error:', error);
});
}
如果需要更多信息,请告诉我:) API 对我来说是一个新领域,我渴望了解如何使其正确工作。
有两个主要问题, 第一个位于片段的以下部分
//...
if (req.body = {} || !req.body) {
res.status(418).send({message:'We need a json'})
return
}
//...
显然你想要做的是检查
req.body
对象是否为空,通过执行这个表达式req.body = {}
你将一个空对象分配给req.body
这是一个真实的表达式,所以它会无论如何输入 if
块,您可以使用 Object.keys(req.body).length
检查对象是否为空,或者检查特定键,如下所示:
//...
const requestBody = req.body || {};
if ("data" in requestBody) {
res.status(200).send({
machine: `dit is je machine met je json ${req}`,
});
return;
}
res.status(418).send({ message: "We need a json" });
//...
客户端代码
fetch('http://localhost:98/machines', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: JSON.stringify({data: "request data"})
//...
第二个问题在
corsOptions
,试试这个:
const corsOptions = {
origin: ["http://192.168.1.99:94", "http://127.0.0.1:94"],
};