"无法获取/"时尝试连接到本地主机:节点.js中的 4000/addProduct 时



我正在使用node.js作为后端服务器。当请求"localhost:4000/addProduct"时,我在浏览器中收到错误"无法获取/addProduct",但是当我请求"localhost:4000"时,它显示输出"Mobile Fair",我不知道这是怎么回事。我的代码如下:

const express = require('express')
const app = express()
require('dotenv').config()
const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.ywjyr.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db(process.env.DB_NAME).collection(process.env.DB_COLLECT);
app.post('/addProduct', (req, res) => {
const newData = req.body;
console.log("adding  new product: ",newData);
})    
console.log("you got error: ",err)
});
app.get('/', (req, res) => {
res.send('Mobile Fair')
})
app.use(function( req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
}); 
app.listen(4000);

我的前端代码如下:

import axios from 'axios';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import Admin from '../Admin/Admin';
const AddProduct = () => {
const [imageUrl, setImageUrl] = useState(null);
const handleImageUpload = (event) => {
console.log(event.target.files[0])
const imageData = new FormData();
imageData.set('key', 'key');
imageData.append('image', event.target.files[0]);
axios.post('uri', imageData)
.then(function (response) {
console.log(response);
setImageUrl(response.data.data.display_url);
})
.catch(function (error) {
console.log(error);
});
}
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = data => {
const newData = {
name: data.name,
memory: data.memory,
price: data.price,
image: imageUrl
}
console.log(newData);

fetch('http://localhost:4000/addProduct', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newData),
})
.then(res=> console.log("server side response: ",res))
};
return (
<div className="d-flex">
<div><Admin /></div>
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<input name="name" placeholder="Enter Name" ref={register({ required: true })} />
{errors.name && <span>This field is required</span>}
<input name="memory" placeholder="Enter Memory" ref={register({ required: true })} />
{errors.memory && <span>This field is required</span>}<br></br>
<input name="price" placeholder="Enter Price" ref={register({ required: true })} />
{errors.memory && <span>This field is required</span>}
<input name="image" type="file" onChange={handleImageUpload} /><br />
<input type="submit" value="Save" />
</form>
</div>
</div>
);
};
export default AddProduct;

试试这个。

fetch(' "localhost:4000/addProduct"', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(newData)
}).then(res => res.json())
.then(res => console.log(res));

此外,为了处理 json 数据,您需要解析它。

const app = express()
app.use(express.json());

更新:只需获取整个 app.post 代码并将其粘贴到该app.get code snippet下方,将其从client.connect回调中删除即可。

app.get('/', (req, res) => {
res.send('Mobile Fair')
})
app.post('/addProduct', (req, res) => {
const newData = req.body;
console.log("adding  new product: ",newData);
})    
console.log("you got error: ",err)

最新更新