如何使用Axios和Express使PUT路由正常工作(而不是返回404错误)?

时间:2018-01-11 17:02:03

标签: node.js express axios

我有一个应用程序可以进行此调用:

handleUpdate (id, data) {
    const url = "/sites/" + id;
    axios.put(url, data)
        .then(res => {
            // handling of response
        })
        .catch(console.error);
}

server.js文件中的路由是:

router.route('/sites/:site_id')
   .put(function(req, res) {
   // handling of update 
})

但是,每次进行handleUpdate调用时,都会收到以下消息:

xhr.js:178 PUT http://localhost:3000/sites/5a39783d09ba9fec39b34d37 404 (Not Found) 

ID是正确的,但我显然没有做对。

以下是server.js的适用部分:

//server.js
'use strict'

//first we import our dependencies...
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

//and create our instances
var app = express();
var router = express.Router();

//set our port to either a predetermined port number if you have set 
it up, or 3001
var port = process.env.API_PORT || 3001;


//db config
var mongoDB =  // my mlab database connection info;
mongoose.connect(mongoDB, { useMongoClient: true })
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

//now we should configure the API to use bodyParser and look for JSON 
data in the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//To prevent errors from Cross Origin Resource Sharing, we will set our 
headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 
'GET,HEAD,OPTIONS,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-
Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-
Request-Method, Access-Control-Request-Headers');

//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
});

//now  we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!'});
});

2 个答案:

答案 0 :(得分:1)

您需要使用method-override包来处理放置请求:

1- install method-override package

npm install method-override --save

2-在你的应用程序中使用它

var express = require('express')
var methodOverride = require('method-override')
var app = express()

// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('X-HTTP-Method-Override'))

3-抓住请求

router.route('/sites/:site_id').put(function(req, res) {
    // handling of update 
})

4- ajax

var config = {
    headers: {
        'X-HTTP-Method-Override', 'PUT'
    }
}

axios.post(url, data, config)
    .then(res => {
        // handling of response
    })
    .catch(console.error);

答案 1 :(得分:1)

我终于意识到我正在将PUT请求指向主应用程序而不是api。一旦我纠正了这个,它就完美了。

一旦问题得到解决,错误就会显得多么明显。

感谢所有帮助过的人。