如何正确配置文件?
我正在尝试提交表单,当我提交表单时,我收到404错误,找不到我的路径/文件。
确切的错误是:
xhr.js:175 POST http://localhost:1337/mail 404 (Not Found)
我的app.js文件是:
var express = require('express');
var mail = require('./routes/mail');
var app = express();
app.use('/mail', mail);
app.use(express.static('dist'));
app.use(express.static('dist/img'));
app.listen(process.env.PORT || 1337);
console.log('Port 1337 is listening');
我的mail.js文件是:
var express = require('express');
var mail = express.Router();
mail.get('/:name/:email/:phone:/message', function(req, res){
console.log('in function');
});
console.log('Made it to mail');
module.exports = mail;
从jsx文件发送代码的函数是:
handleClick(e){
const name = this.state.name;
const email = this.state.email;
const phone = this.state.phone;
const message = this.state.message;
e.preventDefault();
if(name === "" | email === "" | phone === "" | message === ""){
return;
}else{
axios({
method: 'post',
url: '/mail',
data: {name, email, phone, message}
});
}
}
标题显示以下内容:
Request URL:http://localhost:1337/mail
Request Method:POST
Status Code:404 Not Found
Remote Address:[::1]:1337
Response Headers
view source
Connection:keep-alive
Content-Length:18
Content-Type:text/html; charset=utf-8
Date:Mon, 23 Jan 2017 21:17:15 GMT
X-Content-Type-Options:nosniff
X-Powered-By:Express
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:85
Content-Type:application/json;charset=UTF-8
Host:localhost:1337
Origin:http://localhost:1337
Referer:http://localhost:1337/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Request Payload
view source
{name: "Username", email: "user@gmail.com", phone: "1234567891", message: "testing"}
当我运行gulp时,我确实收到了控制台消息“它已发送到邮件”。但是当我提交表单时,它会给我错误" POST http://localhost:1337/mail 404(Not Found)"。
我的目录设置为:
root/
...dist/ (this is where my client.min.js file is where all my front end code is)
...routes/
app.js
答案 0 :(得分:1)
我建议您阅读有关如何定义路线的Express.js文档。 你似乎也不明白请求体(传递给axios数据属性的数据)和url(/ mail /....)
之间的区别您定义的路线只会抓住 GET 请求,但您正在从axios执行 POST 请求,并且您没有任何 POST 请求
你所定义的内容只会像你所做的那样捕获例如这个/mail/john/blablamail/blablaphone/blablamessage
的网址:
app.use('/mail', mail);
//...
mail.get('/:name/:email/:phone/:message',...);
可以简化为:
app.get('/mail/:name/:email/:phone:/message',..);
你正在做的事情对于你似乎不需要的动态网址是有益的。 例如:
// assume url /users/123
app.get('/users/:id', function(req, res){
console.log(req.params.id); // output = 123
});
您需要的是 POST app.post(...);
,如下所示:
app.post('/mail', function(req, res){
console.log(req.body);
// -> {name: "Username", email: "user@gmail.com", phone: "1234567891", message: "testing"}
});
修改强>
还有一件事。为了使req.body成为js对象,你需要body-parser来解析json数据。特别是这一行app.use(bodyParser.json())