简体   繁体   English

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 当试图从 api 路由中的 s3 中提取数据时

[英]Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 when trying to pull data from s3 in an api route

I am trying to pull a JSON file from an S3 bucket.我正在尝试从 S3 存储桶中提取一个 JSON 文件。 Below is my api route which pulls the json file:下面是我的 api 路由,它拉取了 json 文件:

const {GetObjectCommand, S3Client} = require("@aws-sdk/client-s3");
const client = new S3Client() // Pass in opts to S3 if necessary

function getObject (Bucket, Key) {
    return new Promise(async (resolve, reject) => {
        const getObjectCommand = new GetObjectCommand({ Bucket, Key })

        try {
            const response = await client.send(getObjectCommand)

            // Store all of data chunks returned from the response data stream
            // into an array then use Array#join() to use the returned contents as a String
            let responseDataChunks = []

            // Handle an error while streaming the response body
            response.Body.once('error', err => reject(err))

            // Attach a 'data' listener to add the chunks of data to our array
            // Each chunk is a Buffer instance
            response.Body.on('data', chunk => responseDataChunks.push(chunk))

            // Once the stream has no more data, join the chunks into a string and return the string
            response.Body.once('end', () => resolve(responseDataChunks.join('')))
        } catch (err) {
            // Handle the error or throw
            return reject(err)
        }
    })
}

export default async (req, res) => {
    const records = await getObject('bucket', 'file.json')
    res.statusCode = 200;
    res.json(records)
};

and below is how I am fetching the data:以下是我获取数据的方式:

fetch('/api/getRecords').then(res => res.json()).then(data => {console.log(data)})

inspecting the console I get the following errors:检查控制台我收到以下错误:

GET https://www.example.com/api/getRecords 500

and

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

What's weird is that this only happens in my production environment.奇怪的是,这只发生在我的生产环境中。 When I go to my api route in my development environment it works perfectly.当我在我的开发环境中将 go 转到我的 api 路由时,它工作得很好。

I've logged the response from the api route in the production environment and it is returning html instead of the json file which it is supposed to be fetching from the S3 bucket.我已经在生产环境中记录了来自 api 路由的响应,它返回 html 而不是应该从 S3 存储桶中获取的 json 文件。

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width"/>
<meta charSet="utf-8"/>
<title>500: Internal Server Error</title>
<meta name="next-head-count" content="3"/>
<link rel="preload" href="/_next/static/css/0ff82fa55a0f6a71.css" as="style"/><link rel="stylesheet" href="/_next/static/css/0ff82fa55a0f6a71.css" data-n-g=""/><noscript data-n-css=""></noscript>
<script defer="" nomodule="" src="/_next/static/chunks/polyfills-5cd94c89d3acac5f.js"></script>
<script src="/_next/static/chunks/webpack-f4f9fa09c58ec7ec.js" defer=""></script><script src="/_next/static/chunks/framework-bb5c596eafb42b22.js" defer=""></script>
<script src="/_next/static/chunks/main-1d8adce4d7e8417e.js" defer=""></script>
<script src="/_next/static/chunks/pages/_app-d6205651e8a6f164.js" defer=""></script>
<script src="/_next/static/chunks/pages/_error-a3f18418a2205cb8.js" defer=""></script>
<script src="/_next/static/pxh73WL611kWpBZCFSQx6/_buildManifest.js" defer=""></script>
<script src="/_next/static/pxh73WL611kWpBZCFSQx6/_ssgManifest.js" defer=""></script>
<script src="/_next/static/pxh73WL611kWpBZCFSQx6/_middlewareManifest.js" defer=""></script>

</head>

<body>

<div id="__next" data-reactroot="">
    <div style="color:#000;background:#fff;font-family:-apple-system, BlinkMacSystemFont, Roboto, &quot;Segoe UI&quot;, &quot;Fira Sans&quot;, Avenir, &quot;Helvetica Neue&quot;, &quot;Lucida Grande&quot;, sans-serif;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center">
    <div>
    <style>body { margin: 0 }</style>
    <h1 style="display:inline-block;border-right:1px solid rgba(0, 0, 0,.3);margin:0;margin-right:20px;padding:10px 23px 10px 0;font-size:24px;font-weight:500;vertical-align:top">500</h1>
    <div style="display:inline-block;text-align:left;line-height:49px;height:49px;vertical-align:middle">
        <h2 style="font-size:14px;font-weight:normal;line-height:inherit;margin:0;padding:0">Internal Server Error<!-- -->.</h2>
</div>
</div>
</div>
</div>
<script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{},"buildId":"pxh73WL611kWpBZCFSQx6","nextExport":true,"isFallback":false,"gip":true,"scriptLoader":[]}</script>

</body>
</html>

Does anyone know how to fix this?有谁知道如何解决这一问题?

There was an issue with my access keys in my production environment.我的生产环境中的访问密钥存在问题。 Essentially one of my lambdas was getting a permission denied error.本质上,我的一个 lambda 表达式出现了权限被拒绝的错误。 After fixing that issue the problem was resolved.解决该问题后,问题就解决了。 I could not have done it without the help of @Ermiya Eskandary没有@Ermiya Eskandary 的帮助我做不到

make sure you are calling the production server not the development server确保您调用的是生产服务器而不是开发服务器

Angular - 语法错误:意外的标记“<”,“<div id="text_translate"><p> 这是部署在 AWS Amplify 上的 Angular 应用程序</p><p>该应用程序已成功部署,但呈现白屏,并且在控制台上我收到此消息:</p><p> <a href="https://i.stack.imgur.com/dYSXk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dYSXk.png" alt="在此处输入图像描述"></a></p><p> 但我不知道如何解决。</p><hr><p> 这是服务提供者:</p><pre> import { Inject, Injectable } from '@angular/core'; import { CONFIG_TOKEN, UserService, EuiAppConfig, UserDetails, UserPreferences, I18nService, } from '@eui/core'; import { HttpClient } from '@angular/common/http'; import { Observable, of, zip } from 'rxjs'; import { switchMap } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class AppStarterService { defaultUserPreferences: UserPreferences; constructor( protected userService: UserService, protected i18nService: I18nService, @Inject(CONFIG_TOKEN) private config: EuiAppConfig, protected http: HttpClient, ) { } start(): Observable<any> { return zip( this.initUserService().pipe( switchMap((userStatus) => { console.log(userStatus); return this.i18nService.init(); }), ), ); } /** * Fetches user details, * create user: UserState object * then initialise to the UserService on run time */ initUserService(): Observable<any> { return zip( this.fetchUserDetails(), ).pipe( switchMap(([userDetails]) => this.userService.init(userDetails))); } /** * Fetches user details */ private fetchUserDetails(): Observable<UserDetails> { const moduleCoreApi = this.config.modules.core; const url = `${moduleCoreApi.base}${moduleCoreApi.userDetails}`; const user = { userId: 'anonymous' }; if (;url) { return of(user). } return this.http;get<UserDetails>(url); } }</pre><p> 从该代码来看,这是“ <strong>const moduleCoreApi = this.config.modules.core;</strong> ”和“ <strong>moduleCoreApi.base</strong> ”部分</p><pre>import { ModulesConfig } from '@eui/core'; export const MODULES: ModulesConfig = { core: { base: '/api', } };</pre><p> 这是<strong>environment.prod.ts</strong></p><pre> import { EuiEnvConfig } from '@eui/core'; export const environment: EuiEnvConfig = { production: true, enableDevToolRedux: false, envDynamicConfig: { uri: '/assets/env-json-config.json', deepMerge: true, merge: ['modules'], }, };</pre><p> 从该代码中,这是<strong>env-json-config.json</strong></p><pre> { "modules": { "core": { "userDetails": "/user-details" } } }</pre></div> - Angular - SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获(承诺)SyntaxError:JSON.parse:React js 中 JSON 数据的第 1 行第 1 列的意外字符 - Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in React js Uncaught SyntaxError: 意外的标记 '<', " "... JSON at JSON.parse (<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected token '<', "<html> "... is not valid JSON at JSON.parse (<anonymous>) 未捕获的语法错误:Gcloud 中 app.js 中的意外标记“<” - Uncaught SyntaxError: Unexpected token '<' in app.js in Gcloud Angular - 语法错误:意外的标记“<”,“<div id="text_translate"><p> 这是部署在 AWS Amplify 上的 Angular 应用程序</p><p>该应用程序已成功部署,但呈现白屏,并且在控制台上我收到此消息:</p><p> <a href="https://i.stack.imgur.com/dYSXk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dYSXk.png" alt="在此处输入图像描述"></a></p><p> 但我不知道如何解决。</p><hr><p> 这是服务提供者:</p><pre> import { Inject, Injectable } from '@angular/core'; import { CONFIG_TOKEN, UserService, EuiAppConfig, UserDetails, UserPreferences, I18nService, } from '@eui/core'; import { HttpClient } from '@angular/common/http'; import { Observable, of, zip } from 'rxjs'; import { switchMap } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class AppStarterService { defaultUserPreferences: UserPreferences; constructor( protected userService: UserService, protected i18nService: I18nService, @Inject(CONFIG_TOKEN) private config: EuiAppConfig, protected http: HttpClient, ) { } start(): Observable<any> { return zip( this.initUserService().pipe( switchMap((userStatus) => { console.log(userStatus); return this.i18nService.init(); }), ), ); } /** * Fetches user details, * create user: UserState object * then initialise to the UserService on run time */ initUserService(): Observable<any> { return zip( this.fetchUserDetails(), ).pipe( switchMap(([userDetails]) => this.userService.init(userDetails))); } /** * Fetches user details */ private fetchUserDetails(): Observable<UserDetails> { const moduleCoreApi = this.config.modules.core; const url = `${moduleCoreApi.base}${moduleCoreApi.userDetails}`; const user = { userId: 'anonymous' }; if (;url) { return of(user). } return this.http;get<UserDetails>(url); } }</pre><p> 从该代码来看,这是“ <strong>const moduleCoreApi = this.config.modules.core;</strong> ”和“ <strong>moduleCoreApi.base</strong> ”部分</p><pre>import { ModulesConfig } from '@eui/core'; export const MODULES: ModulesConfig = { core: { base: '/api', } };</pre><p> 这是<strong>environment.prod.ts</strong></p><pre> import { EuiEnvConfig } from '@eui/core'; export const environment: EuiEnvConfig = { production: true, enableDevToolRedux: false, envDynamicConfig: { uri: '/assets/env-json-config.json', deepMerge: true, merge: ['modules'], }, };</pre><p> 从该代码中,这是<strong>env-json-config.json</strong></p><pre> { "modules": { "core": { "userDetails": "/user-details" } } }</pre></div> - Angular - SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON 当尝试从 S3 发送文件作为 email 附件时,字节类型的 Object 不是 JSON 可序列化的 - Object of type bytes is not JSON serializable when trying to send a file from S3 as an email attachment 在 s3 意外令牌 < 上托管的 React 应用程序 - React app hosted on s3 unexpected token < 将 reactjs 应用程序部署到 aws amplify 会导致白屏并出现错误“Uncaught SyntaxError: Unexpected token '<'” - Deploying reactjs app to aws amplify results in white screen with error "Uncaught SyntaxError: Unexpected token '<'" 使用 Amazon S3 循环运行数据拉取 - Running on loop on a data pull with Amazon S3 我收到多个错误:尝试在 aws s3 存储桶中上传文件时出现意外字段 - I am getting multer error : unexpected field when i was trying to upload files in aws s3 bucket 将 json 文件从一个 s3 存储桶复制到另一个 s3 存储桶时,无法识别 Json 文件? - Json file is not recognising when copy json files from one s3 bucket to another s3 bucket?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM