我有一个为我的graphq服务的节点服务器。然后,我在前端next.js项目中使用它。现在,我想向其中一个页面添加联系表单。现在,我在next.js项目中有一个处理此问题的server.js文件。参见下面的代码。
我想做的是能够在graphql服务器上调用一个函数,该函数可以传递表单字段,然后发送电子邮件。
不使用express就能做到吗?
graphql.js(在单独的文件夹中)
const {
makeRemoteExecutableSchema,
introspectSchema
} = require("graphql-tools");
const { HttpLink } = require("apollo-link-http");
const fetch = require("node-fetch");
const { GraphQLServer } = require("graphql-yoga");
// Apollo link with the uri of GraphQL API
const link = new HttpLink({
uri: "https://api-euwest.graphcms.com/v1/cjsnh2qfp3099e01fjurcavk7i/master",
fetch
});
async function startServer() {
const schema = await introspectSchema(link);
const executableSchema = makeRemoteExecutableSchema({
schema,
link
});
const server = new GraphQLServer({ schema: executableSchema });
server.start(
{
cors: {
credentials: true,
origin: ["http://localhost:3000"] // your frontend url.
}
},
deets => {
console.log(
`Server is now running on port http://localhost:${deets.port}`
);
}
);
}
startServer();
server.js
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const nodemailer = require('nodemailer');
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'adamjwright32@gmail.com',
pass: 'Zeppelin32'
}
});
const send = ({ email, name, message }) => {
const mailOptions = {
from: 'hello@adamwright.dev',
to: 'adam.wright90@yahoo.co.uk',
subject: `New message from ${name}`,
html: `<div>
<strong>Name:</strong>${name}<br>
<strong>Email:</strong>${email}<br>
<strong>Message:</strong><br>${message}
</div>`
}
transporter.sendMail(mailOptions, function (err, info) {
if (err)
console.log("err", err)
else
console.log("info", info);
});
}
app.prepare().then(() => {
const server = express()
server.use(bodyParser.json())
server.get('*', (req, res) => {
return handle(req, res)
})
server.post('/api/contact', (req, res) => {
send(req.body)
res.send('success')
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Read on http://localhost:3000')
})
})