简体   繁体   English

尝试连接到 node.js 中的 localhost:4000/addProduct 时出现“无法获取 /”

[英]“Cannot GET /” when trying to connect to localhost:4000/addProduct in node.js

I am working with node.js as backend server.我正在使用 node.js 作为后端服务器。 When requesting to "localhost:4000/addProduct" I got the error "Cannot GET /addProduct" in the browser but when I request to "localhost:4000" it is showing the output 'Mobile Fair' and I do not know what is the matter.当请求“localhost:4000/addProduct”时,我在浏览器中收到错误“Cannot GET /addProduct”,但是当我请求“localhost:4000”时,它显示 output 'Mobile Fair',我不知道是什么事情。 My code is as follows:我的代码如下:

 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);

My front end code is given below:我的前端代码如下:

 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;

Try this.尝试这个。

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));

Also in order to handle json data you need to parse it.此外,为了处理 json 数据,您需要对其进行解析。 add this line after your在你之后添加这一行

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

Update: just take your entire app.post code and paste it below that app.get code snippet , remove it from your client.connect callback.更新:只需将您的整个 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM