简体   繁体   中英

getting Request failed 404 error on Node.js code which uses Axios

I am trying to link 2 server files to perform some action with URL, by using Node.js + express + Axios

link structure is

FE Client [UI (VUE) -> PostService.js] -> BE Server [index.js -> posts_users.js -> DB]

The situation now I got is...

  1. Enroll new user works perfectly(FE UI (vue) -> PostService.js(insert_Users_Post) -> BE posts_users.js(router.post('/'))

  2. other two(modification and delete) is getting the following errors

    main.js?attr=gU7jfEErMGN47FOrFiB547YfT_VvvSwaYNqc5Th-l4B1v8b4BwucNhxWmVsYhNG6uoWufyN_zukG_sameBaZuQ:1078 PATCH http://localhost:8080/User_Management/api/posts_users/6049b4cbc3c1a94668af9e64 404 (Not Found)

    vue.esm.js?a026:1897 Error: Request failed with status code 404 at createError (createError.js?2d83:16) at settle (settle.js?467f:17) at XMLHttpRequest.handleLoad (xhr.js?b50d:62)

the weird thing is..

  1. on PostService.js code, I checked it receives '_id' value well [ex) _id = 6049a5238651e35bc0cf449c]
  2. and other UI option is also referencing a similar structure of code, but working well....

Have any tips....to fix errors..?

here is my PostService.js code

import axios from "axios";    
const url_users = "api/posts_users/";

class PostService {

  //Create users post 
  static insert_Users_Post(createdAt, userID, firstName, lastName, max_temp, phoneNum, emailAddr, department, deviceName, role, status) {
    return axios.post(url_users, {
      createdAt, userID, firstName, lastName, max_temp, phoneNum, emailAddr, department, deviceName, role, status
    });
  }

  //update users post
  static update_Users_Post(_id, createdAt, userID, firstName, lastName, max_temp, phoneNum, emailAddr, department, deviceName, role, status) {
    return axios.patch(url_users+ `${_id}`, {
      createdAt, userID, firstName, lastName, max_temp, phoneNum, emailAddr, department, deviceName, role, status
    });
  }

  //delete users post
  static delete_Users_Post(_id) {
    return axios.delete(`${url_users}${_id}`);
  }
}

and this is my posts_users.js code

const express = require('express');
const mongodb = require('mongodb');
const router = express.Router();
var config = require('../../../config');

// Add User Post
router.post('/', async(req, res) => {
    const posts = await loadPostsCollection_Users();
    await posts.insertOne({         
        userID: req.body.userID,
        firstName: req.body.firstName, 
        lastName: req.body.lastName,               
        phoneNum: req.body.phoneNum,
        emailAddr: req.body.emailAddr,
        department: req.body.department,
        deviceName: req.body.deviceName,
        role: req.body.role,
        createdAt : req.body.createdAt,
        updatedAt : req.body.createdAt,
        createdVia:"Web",                
        status: req.body.status,            
        active: "false",
        max_temp: req.body.max_temp,
    });
    res.status(201).send();
});

// Modify User Post
router.patch('/:id', async(req, res) => {
    const posts = await loadPostsCollection_Users();
    await posts.updateOne(
        { "_id" : new mongodb.ObjectID(req.params.id) },
        {$set: {
            "userID": req.body.userID,
            "firstName": req.body.firstName, 
            "lastName": req.body.lastName,               
            "phoneNum": req.body.phoneNum,
            "emailAddr": req.body.emailAddr,
            "department": req.body.department,
            "deviceName": req.body.deviceName,
            "role": req.body.role,
            "updatedAt" : req.body.createdAt,
            "createdVia":"Web",                
            "status": req.body.status,            
            "active": "false",
            "max_temp": req.body.max_temp
        }},     
        { upsert: true }
    );
    res.status(201).send();
});
    
// Delete User Post
router.delete('/:id', async(req, res) => {
    const posts = await loadPostsCollection_Users();
    await posts.deleteOne({
        _id: new mongodb.ObjectID(req.params.id)
    });
    res.status(200).send();
});

async function loadPostsCollection_Users() {
    const client = await mongodb.MongoClient.connect(`mongodb://${config.DB_IPAddr}:${config.DB_PortNo}/tms`, {
        useNewUrlParser: true
    });
    return client.db('tms').collection('integrated_users');
}

module.exports = router;

and lastly this is my BE index.js code

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');    
const app = express();

// Middleware
app.use(bodyParser.json());
app.use(cors());

const posts_users = require('./routes/api/posts_users');

app.use('/api/posts_users', posts_users);

// Handle production
if(process.env.NODE_ENV === 'production'){
    //Static folder
    app.use(express.static(__dirname + '/public/'));

    //Handle SPA
    app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'));
}

const port = process.env.PORT || 5002;
app.listen(port, () => console.log(`Server started on port ${port}`));

Please make sure base url appended properly during Axios call.

const url_users = "api/posts_users/";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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