问题描述
我第一次建立一个Express实例,我遇到了一个问题,即一切都在本地运行,但是在部署后向该路由发送后继请求会响应:
无法加载资源:服务器响应状态为405 (不允许)
我已经包含以下相关代码:
server / index.js
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname,'build')));
const routes = require('./routes')(express)
require('./db')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/',function (req,res) {
res.sendFile(path.join(__dirname,'build','index.html'));
});
app.listen(process.env.PORT || 8080);
app.use('/',routes);
routes / index.js
var mongoose = require("mongoose");
const randomId = require('random-id');
const Submissions = require('../api/Submissions')
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
router.route('/submission')
.post((req,res) => {
let newSubmission = new Submissions(req.body);
newSubmission._id = randomId(17,'aA0');
// Save the new model instance,passing a callback
newSubmission.save(function(err,response) {
if (err) {
console.log(err)
} else {
res.setHeader('Content-Type','application/json');
res.json({'success':true})
}
// saved!
})
});
return router;
}
client.js
let submission = {
name: this.state.newSubmission.name.trim(),body: this.state.newSubmission.body.trim(),email: this.state.newSubmission.email.trim(),};
const requestOptions = {
method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(submission),};
fetch("/submission",requestOptions)
.then((response) =>
response.json().then((data) => ({
data: data,status: response.status,}))
)
.then((res) => {
if (!res.data.success) {
notifier.warning('Failed to submit');
} else {
notifier.success('Submission successful');
}
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)