gpt4 book ai didi

javascript - 使用 angular.js 和 ExpressJS 的 POST 请求 404(未找到)

转载 作者:行者123 更新时间:2023-11-30 17:22:01 25 4
gpt4 key购买 nike

我正在尝试使用 AngularJS 向我的 ExpressJS 服务器发送请求:

angular.module('app').controller('contactCtrl', function($scope, $http) {
$scope.envoyer = function(nom, organisation, courriel, telephone, message){
$http.post('/contact', {nom:nom, organisation:organisation, courriel:courriel, telephone:telephone, message:message}).then(function(error, response){
if(response.data.success){
console.log('sent!');
}
});
}
});

这是来自服务器的代码:

var mailer = require('nodemailer');

var EMAIL_ACCOUNT_EMAIL = 'aaa@gmail.com';
var EMAIL_ACCOUNT_PASSWORD = 'aaa';

var smtpTransport = mailer.createTransport({
service: "Gmail",
auth: {
user: EMAIL_ACCOUNT_EMAIL,
pass: EMAIL_ACCOUNT_PASSWORD
}
});

app.post('/contact', function(req, res, next){
var success = true;
var mailOptions = {
to: 'azez@email.com',
subject: 'qsdxwccvfd',
html: 'sqdqsdq'
};

smtpTransport.sendMail(mailOptions, function(error, res){
if(error){
console.log('[ERROR] Message NOT sent: ', error);
success = false;
} else {
console.log('[INFO] Message sent: ' + res.message);
}
next(error, success);
});
});

服务器执行请求后,我在客户端收到此错误消息:

POST http://localhost:3002/contact 404 (Not Found) angular.js:8495
(anonymous function) angular.js:8495
sendReq angular.js:8291
$http.serverRequest angular.js:8025
wrappedCallback angular.js:11498
wrappedCallback angular.js:11498
(anonymous function) angular.js:11584
Scope.$eval angular.js:12608
Scope.$digest angular.js:12420
Scope.$apply angular.js:12712
(anonymous function) angular.js:18980
jQuery.event.dispatch jquery.js:4409
elemData.handle

我认为它来自 AngularJS 代码的第四行,但我无法找到修复它的方法。请问我该如何解决?

最佳答案

为了向浏览器发送成功响应,中间件末尾对 next 的调用应替换为如下内容:

res.set('Content-Type', 'application/json'); // tell Angular that this is JSON
res.send(JSON.stringify({success: success}));

这些行告诉 express 返回标记为成功的响应,主体为 JSON 格式,对象仅具有“success”属性。

但是,为了使其正常工作,您需要重命名您在 smtpTransport.sendMail 的回调中使用的参数,因为您调用了 res,所以它是当前从中间件中隐藏 res 对象。所以将该函数的 header 更改为如下所示:

smtpTransport.sendMail(mailOptions, function(error, mailRes){

...然后您当然必须更改后面的日志行以使用 mailRes 而不是 res

关于javascript - 使用 angular.js 和 ExpressJS 的 POST 请求 404(未找到),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24977412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com