我正在使用带有Nodejs / ExpressJS / DynamoDB服务器的AWS lambda函数上的Nextjs(我知道我可以为此使用棱镜)构建一个简单的博客,它可以在我的本地工作,但是在dev上无法按某些get方法工作
我正在使用apisauce进行API get调用(我也尝试过axios和isomorphic-unfecth):
import { create } from 'apisauce'
// define the api
const api = create({
baseURL: apiConfig.baseURL,
headers: { Accept: 'application/vnd.github.v3+json' },
timeout: 60000
})
const getPostBySlug = async slug => {
return await api.get(`/api/get-post-by-slug/${slug}`);
}
奇怪的是,下面的请求返回了预期的数据,只有那些通过参数的请求才返回那个奇怪的长字符串。
const posts = async () => {
return await api.get(`/api/blog-posts`);
}
可能与以下后端相关吗?
server.get("/p/:slug", async (req, res) => {
const actualPage = "/post";
const queryParams = { slug: req.params.slug };
app.render(req, res, actualPage, queryParams);
})
这是我的后端代码:
*** lambda.js ***
'use strict'
const { app, server } = require("./server");
const awsServerlessExpress = require("aws-serverless-express");
const binaryMimeTypes = require('./binaryMimeType');
exports.handler = (event, context, callback) => {
app.prepare().then(() => {
if( !process.env.BASE_URL ) {
delete event.multiValueHeaders;
}
if (event.source === 'serverless-plugin-warmup') {
console.log('WarmUP - Lambda is warm!')
return callback(null, 'Lambda is warm!')
}
return awsServerlessExpress.proxy(
awsServerlessExpress.createServer(server, null, binaryMimeTypes),
event,
context
);
});
};
****server.js****
require('dotenv').config();
const express = require("express")
const compression = require('compression')
const next = require("next")
const bodyParser = require("body-parser")
const cors = require("cors")
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
global.fetch = require('node-fetch')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== "production"
const app = next({ dev })
const handle = app.getRequestHandler()
const ignoreFavicon = (req, res, next) => {
if (req.originalUrl === '/favicon.ico') {
res.status(204).json({nope: true});
} else {
next();
}
}
const verifyToken = require("./service/verifyToken")
const blog = require("./controllers/postsController");
const { createSitemap } = require("../utils/generateSitemap");
const createServer = () => {
const server = express()
server.use((req, res, next) => {
res.removeHeader("X-Powered-By");
res.header("Access-Control-Allow-Methods", "OPTIONS,GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "*");
res.header("Access-Control-Allow-Origin", "*");
if (
req.headers["access-control-request-headers"] &&
req.headers["access-control-request-headers"] !== ""
) {
res.header(
"Access-Control-Allow-Headers",
req.headers["access-control-request-headers"]
);
}
next();
});
/**
* Setting the payload limit to 50mb
*/
server.use(bodyParser.json({ limit: "150mb" }));
server.use(
bodyParser.urlencoded({
limit: "150mb",
extended: true,
parameterLimit: 50000,
})
);
server.use(awsServerlessExpressMiddleware.eventContext());
server.use(cors())
server.use(ignoreFavicon)
// compress all responses
server.use(compression());
server.get("/p/:slug", async (req, res) => {
const actualPage = "/post";
const queryParams = { slug: req.params.slug };
app.render(req, res, actualPage, queryParams);
})
server.get("/e/:id", async (req, res) => {
const actualPage = "/edit";
const queryParams = { id: req.params.id };
app.render(req, res, actualPage, queryParams);
})
server.get("/c/:cat", async (req, res) => {
const actualPage = "/category";
const queryParams = { cat: req.params.cat };
app.render(req, res, actualPage, queryParams);
})
server.get("/api/blog-posts", async (req, res) => {
const data = await blog.getPosts();
console.log("/api/blog-posts", data);
res.send(data);
})
server.get("/api/list-posts", verifyToken, async (req, res, next) => {
const data = await blog.listPosts();
console.log("/api/list-posts", data);
res.send(data);
})
server.get("/api/get-post-by-category/:category", async (req, res) => {
const category = req.params.category;
const data = await blog.getPostsByCategory(category);
console.log("/api/get-post-by-category/:category", data);
res.send(data);
})
server.post("/api/post", verifyToken, async (req, res, next) => {
const data = await blog.createPost(req.body);
console.log("/api/post", data);
res.send(data);
})
server.post("/api/delete-post", async (req, res) => {
const data = await blog.deletePost(req.body.id);
console.log("/api/delete-post", data);
res.send(data);
})
server.get("/api/get-post-by-id/:id", async (req, res) => {
const id = req.params.id;
const data = await blog.getBlogPostById(id);
console.log("/api/get-post-by-id/:id", data);
res.send(data);
})
server.get("/api/get-post-by-slug/:slug", async (req, res) => {
const slug = req.params.slug;
const data = await blog.getPostBySlug(slug);
console.log("/api/get-post-by-slug/:slug", data);
res.send(data);
})
server.post('/api/update', async (req, res) => {
const data = await blog.updatePost(req.body);
console.log("/api/update", data);
res.send(data);
})
server.get('/robots.txt', function (req, res) {
res.type('text/plain');
res.send("User-agent: *\nDisallow: /");
});
server.get('/sitemap.xml', (req, res) => createSitemap(res));
server.get('*', (req, res) => {
return handle(req, res)
})
server.use(function (err, req, res, next) {
if ( err.name === 'UnauthorizedError' ) {
res.status(401).send({
title: 'Unauthorized',
detail: 'Unauthorized Access!'
});
}
})
return server
};
const server = createServer()
if (!process.env.LAMBDA) {
app.prepare().then(() => {
server.listen(port, err => {
if (err) throw err
console.log(`Ready on http://localhost:${port}`)
})
}).catch((ex) => {
console.error('ex.stack:', ex.stack);
process.exit(1);
});
}
exports.app = app
exports.server = server
当我在Cloudwatch上管理日志数据时,它正在返回预期的对象,例如
但是在前端,这是显示的内容:
该博客托管在AWS Cloudfront上,并使用API Gateway来处理请求。我不确定这是否与标头有关,但是后端上的所有功能都按预期运行,我能够从DynamoDb中获取数据。
非常感谢您的帮助。