我正在尝试创建一个可以与我的 api 交互的简单前端。目前 api 没问题,当使用 POSTMAN 客户端发送请求时,我可以获取数据并发布数据。到目前为止,我可以从服务器获取数据并将其加载到前端,但尝试发布到 api 是我遇到的挑战。
这是我尝试发布数据时遇到的错误 脚本.js:45
POST http://127.0.0.1:5500/users net::ERR_ABORTED 405 (Method Not Allowed)
(anonymous) @ script.js:45
为了向您展示我所做的事情,这是我要提交的表格
<form>
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname"><br>
Age: <input type="number" name="age" id="age"><br>
<button type="submit">Send to backend</button>
</form>
下面是前端包含的javascript代码
// function updatePost(){
const firstname = document.getElementById('firstname')
const lastname = document.getElementById('lastname')
const age = document.getElementById('age')
const button = document.querySelector('button')
button.addEventListener('click',(e)=>{
e.preventDefault()
var obj = {
firstname:firstname.value,
lastname:lastname.value,
age:age.value
};
fetch('/users',{
method:"POST",
// headers:{
// "content-type":"application/json"
// },
body:JSON.stringify(obj)
})
})
// }
// updatePost()
下面是我的帖子路由,这是服务器端逻辑
app.post('/users', async(req,res)=>{
var {firstname,lastname,age} = req.body
console.log(req.body)
let conn;
try {
console.log(firstname,lastname,age)
conn = await pool.getConnection()
const result = await conn.query("insert into info (firstname, lastname,age) VALUES (?, ?, ?)",[firstname,lastname,age])
res.json({
"res":"your code is working denis"
})
} catch (error) {
res.send(error)
}finally {
// await poolModule.releaseConn(conn);
conn.release()
}
}
)
app.listen('3008',()=>{
console.log('server is working')
})
我觉得我缺少一些东西,非常感谢您的帮助。如果需要更多信息,我可以将所有代码放在这里以便重现错误。谢谢。
您正在通过 Live Server 扩展打开 HTML 页面。这是一个静态 Web 服务器,主要用于提供静态资源(HTML、CSS、JavaScript、图像等)。
当您尝试使用
fetch('/users', { method: 'POST' })
时,该 POST 请求将发送到无法处理它的 Live Server。您应该将请求发送至您的 Express 服务。
为此,有两种选择...
使用 Express 来代替 Live Server 来提供静态内容。例如
app.use(express.static('path/to/html/files'));
然后打开浏览器
http://localhost:3008/...
现在任何相对或仅路径请求(如
/users
)都将到达正确的位置。
或...
在 Express 应用中启用 CORS 并发出跨源请求。
cors
中间件
npm i cors
启用它
// Enable CORS first
app.use(cors({
origin: ['http://localhost:5500'],
}));
// then other request-handling middleware, eg
app.use(express.json());
向 Express 提出您的要求
fetch('http://localhost:3008/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(obj),
})