我有一个server.js,其侦听端口为4000。请检查以下代码
const port = 4000;
const express = require('express')
const cors = require('cors')
const app = express()
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "musteri"
});
con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
app.use(cors());
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.get('/user', function(req, res, next) {
console.log(req);
con.query('select * from musteri_ayarlar', function (error, results, fields) {
if(error) throw error;
res.send(JSON.stringify(results));
});
});
app.listen(port, (err) => {
if(err) { console.log(err) };
console.log('Service Port ' + port + ' started')
})
使用上述代码监听 localhost:4000 /用户
当我调用 localhost:4000 / user 从mysql返回记录时,我可以从chrome进行访问而没有任何问题。
当我从获取api调用 localhost:4000 / user 地址时,我的问题就开始了。
它说 POST http://localhost:4000/user 404(未找到)
这是我从app.jsx中获取的代码
componentDidMount() {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Content-Type': 'applications/json'
},
body: JSON.stringify({ username: "John", password: 30 })
};
fetch(`http://localhost:4000/user`, requestOptions)
.then(handleResponse => handleResponse.text())
.then(user => {
console.log(user);
localStorage.setItem('user', JSON.stringify(user));
return user;
});
}```
What is wrong with my fetchAPI code? Thanks.
答案 0 :(得分:0)
app.get('/user', function(req, res, next) {
console.log(req);
con.query('select * from musteri_ayarlar', function (error, results, fields) {
if(error) throw error;
res.send(JSON.stringify(results));
});
});
您已经在此处创建了一个获取端点
更改获取中的请求方法
const requestOptions = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Content-Type': 'applications/json'
}
};
GET不接受任何正文,因为您没有使用请求,这将满足