由于某种原因,我无法从 server.js 到达 API 端点。使用 Spotify API。 这是我的 server.js:
// server.js
const express = require('express');
const app = express();
const dotenv = require('dotenv').config()
const clientSecret = secret
const clientId = id
app.use(express.json());
// PARAMS
const authParameters = {
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
},
body: 'grant_type=client_credentials&client_id=' + clientId + '&client_secret=' + clientSecret
}
app.get('/message', (req, res) => {
res.json({ message: "Hello from server!" })
})
app.get('/spotify/token', async (req, res) => {
try {
// Fetch data from the Spotify APIa
const data = await fetch('https://accounts.spotify.com/api/token', authParameters)
console.log("DATA!!!!", data)
res.json(data)
} catch (error) {
console.error('Ran into an error:', error)
res.status(500).json({ error: 'Server error' })
}
});
const PORT = 3000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
});
这是我的package.json:
{
"name": "music-playlist-transfer-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"devStart": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2",
"nodemon": "^3.0.1"
}
}
这是该函数在我的客户端的使用:
const getToken = async () => {
const data = await fetch('/spotify/token')
console.log(data)
const result = await data.json(data)
console.log(result)
return result.access_token
}
export default getToken
以下是该函数在前端的使用:
import React, { useEffect } from "react"
import getToken from "../api/getToken"
import { Button } from "@mui/material"
const LandingPage = () => {
const handleTestButton = async () => {
console.log("here")
const token = await getToken()
console.log(token)
return token
}
return (
<>
<Button onClick={() => handleTestButton()} variant={"outlined"}>asd</Button>
</>
)
}
export default LandingPage
我正在使用 Nodemon 来启动服务器。每当我尝试单击按钮来测试 API 调用时,都会收到错误消息:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
和对象:Response { type: "basic", url: "http://localhost:5173/spotify/token", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers(8), body: ReadableStream, bodyUsed: false } getToken.js:20:13
我在前端工作中使用了相同的代码,它为我提供了所需的访问令牌。
我访问
http://localhost:3000/spotify/token
时在终端收到的对象是:
DATA!!!! Response {
[Symbol(realm)]: null,
[Symbol(state)]: {
aborted: false,
rangeRequested: false,
timingAllowPassed: true,
requestIncludesCredentials: true,
type: 'default',
status: 400,
timingInfo: {
startTime: 3310.630542039871,
redirectStartTime: 0,
redirectEndTime: 0,
postRedirectStartTime: 3310.630542039871,
finalServiceWorkerStartTime: 0,
finalNetworkResponseStartTime: 0,
finalNetworkRequestStartTime: 0,
endTime: 0,
encodedBodySize: 85,
decodedBodySize: 0,
finalConnectionTimingInfo: null
},
cacheState: '',
statusText: 'Bad Request',
headersList: HeadersList {
cookies: [Array],
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: null
},
urlList: [ [URL] ],
body: { stream: undefined }
},
[Symbol(headers)]: HeadersList {
cookies: [
'__Host-device_id=AQBrs3chlvJceJxn00EzwIWmJ3pi3HP1dnVssqyrBWAgMdxpAwGR4y6KkZ56p8n0yzebgru7AxscYPa1PavGUtJkTaQEW-EBsNU;Version=1;Path=/;Max-Age=2147483647;Secure;HttpOnly;SameSite=Lax',
'sp_tr=false;Version=1;Domain=accounts.spotify.com;Path=/;Secure;SameSite=Lax'
],
[Symbol(headers map)]: Map(13) {
'date' => [Object],
'content-type' => [Object],
'set-cookie' => [Object],
'sp-trace-id' => [Object],
'x-envoy-upstream-service-time' => [Object],
'server' => [Object],
'strict-transport-security' => [Object],
'x-content-type-options' => [Object],
'content-encoding' => [Object],
'vary' => [Object],
'via' => [Object],
'alt-svc' => [Object],
'transfer-encoding' => [Object]
},
[Symbol(headers map sorted)]: null
}
}
我得到的 JSON 是一个空对象。 不太确定发生了什么,洞察力将不胜感激!谢谢。
在此行:
const data = await fetch('https://accounts.spotify.com/api/token', authParameters)
变量
data
现在是一个已确定的 Promise,因此要访问该 Promise 的返回值,如果要将其发送到客户端,您需要将 data
转换为 JSON。像这样更新:
const data = await fetch('https://accounts.spotify.com/api/token', authParameters)
console.log("DATA!!!!", data)
res.json(await data.json())