質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

Q&A

解決済

1回答

2927閲覧

axiosでpostができない

sakana_motoki

総合スコア16

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

0グッド

0クリップ

投稿2021/01/17 16:40

編集2021/01/18 08:09

nodeを使って会員登録が必要なwebアプリのチャット機能を実装しています。
routes/message.jsというファイルでデータベースから会員情報を取得し、
public/custom.jsというファイルで会員情報を受け取りたいと考えております

そのためにaxiosを使ってデータの受け渡しをしようと思って

javascript

1const axiosBase = require('axios'); 2const axios=axiosBase.create({ 3 baseURL:'http://localhost:3000', 4 headers:{'Content-Type': 'application/json'}, 5 responseType:'json' 6}); 7async function useaxios(){ 8await axios.post('/message',{ 9 firstName:'Fred', 10 lastName:'Flintstone' 11}) 12.then(response=>{ 13 console.log('いけてる',response.data); 14}).catch(error=>{ 15 console.log(error); 16}); 17}

と書いてみました。
axiosでの通信はいけているようですが
response.dataの中身が

html

1 <!DOCTYPE html> 2<html lang="ja"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <link rel="stylesheet" href='/stylesheets/organizer-login.css'> 9 <title>sign-up</title> 10</head> 11 12 13 14 15 16<body> 17~~~~~~~~~~~省略 18</body> 19 20</html> 21

となぜかhtmlファイルが表示されます、なぜでしょうか?
上記axiosのコードはほぼ公式のreadmeの内容と同じですので間違いはないとは思いますが
ほとんど素人に近いので間違いがあるかもしれません

console.log('いけてる',response.data);

解決の糸口になりそうなこと

console.log('いけてる',response);
にしたら下のようになり一応反映されていることがわかります
ただ、dataが2個あってresponse.dataとするとhtmlの方が出力されてしまいます。
原因と対策方法がわからないので教えていただきたいです

追記

response.confing.data
としてconsole.logをしたらターミナル上に想定していた値が返ってきました。
しかしaxios.getしてもundefinedとなり値を取得できませんなぜでしょうか?
nodeではaxiosが使えないなんてことがあるのでしょうか?

いけてる { status: 200, statusText: 'OK', headers: { 'x-powered-by': 'Express', 'content-type': 'text/html; charset=utf-8', 'content-length': '1276', etag: 'W/"4fc-Xi7sOKe6PVfU4AVFFZ0dEggSnUU"', 'set-cookie': [ 'connect.sid=s%3AnbeFFjUiZPlLupsF0KPtLc8j7GMxiuys.QKRAXjuBS6zXTQq8qOQi1vFe%2BDF1frGoXvIR0tlj8xU; Path=/; HttpOnly' ], date: 'Sun, 17 Jan 2021 16:25:25 GMT', connection: 'close' }, config: { url: '/message', method: 'post', data: '{"firstName":"Yohei","lastName":"Munesada"}', headers: { Accept: 'application/json, text/plain, */*', 'User-Agent': 'axios/0.21.1' }, baseURL: 'http://localhost:3000', transformRequest: [ [Function: transformRequest] ], transformResponse: [ [Function: transformResponse] ], timeout: 0, adapter: [Function: httpAdapter], responseType: 'json', xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: [Function: validateStatus] }, request: <ref *1> ClientRequest { _events: [Object: null prototype] { socket: [Function (anonymous)], abort: [Function (anonymous)], aborted: [Function (anonymous)], connect: [Function (anonymous)], error: [Function (anonymous)], timeout: [Function (anonymous)], prefinish: [Function: requestOnPrefinish] }, _eventsCount: 7, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: true, chunkedEncoding: false, shouldKeepAlive: false, _defaultKeepAlive: true, useChunkedEncodingByDefault: false, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: 0, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: Socket { connecting: false, _hadError: false, _parent: null, _host: 'localhost', _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 7, _maxListeners: undefined, _writableState: [WritableState], allowHalfOpen: false, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Circular *1], [Symbol(async_id_symbol)]: 289, [Symbol(kHandle)]: [TCP], [Symbol(kSetNoDelay)]: false, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(RequestTimeout)]: undefined }, _header: 'GET /organizer-login HTTP/1.1\r\n' + 'Accept: application/json, text/plain, */*\r\n' + 'User-Agent: axios/0.21.1\r\n' + 'Host: localhost:3000\r\n' + 'Connection: close\r\n' + '\r\n', _keepAliveTimeout: 0, _onPendingData: [Function: noopPendingOutput], agent: Agent { _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, defaultPort: 80, protocol: 'http:', options: [Object], requests: {}, sockets: [Object], freeSockets: {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'fifo', maxTotalSockets: Infinity, totalSocketCount: 1, [Symbol(kCapture)]: false }, socketPath: undefined, method: 'GET', maxHeaderSize: undefined, insecureHTTPParser: undefined, path: '/organizer-login', _ended: true, res: IncomingMessage { _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, socket: [Socket], httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: true, headers: [Object], rawHeaders: [Array], trailers: {}, rawTrailers: [], aborted: false, upgrade: false, url: '', method: null, statusCode: 200, statusMessage: 'OK', client: [Socket], _consuming: false, _dumped: false, req: [Circular *1], responseUrl: 'http://localhost:3000/organizer-login', redirects: [], [Symbol(kCapture)]: false, [Symbol(RequestTimeout)]: undefined }, aborted: false, timeoutCb: null, upgradeOrConnect: false, parser: null, maxHeadersCount: null, reusedSocket: false, host: 'localhost', protocol: 'http:', _redirectable: Writable { _writableState: [WritableState], _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _options: [Object], _ended: true, _ending: true, _redirectCount: 1, _redirects: [], _requestBodyLength: 43, _requestBodyBuffers: [], _onNativeResponse: [Function (anonymous)], _currentRequest: [Circular *1], _currentUrl: 'http://localhost:3000/organizer-login', _isRedirect: true, [Symbol(kCapture)]: false }, [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype] { accept: [Array], 'user-agent': [Array], host: [Array] } }, data: '<!DOCTYPE html>\n' + '<html lang="ja">\n' + '\n' + ' <head>\n' + ' <meta charset="UTF-8">\n' + ' <meta name="viewport" content="width=device-width, initial-scale=1.0">\n' + ' <meta http-equiv="X-UA-Compatible" content="ie=edge">\n' + ` <link rel="stylesheet" href='/stylesheets/organizer-login.css'>\n` + ' <title>sign-up</title>\n' + '</head>\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '<body>\n' + ' ~~~~~~~~~~~~~~省略~~~~~~~~~~~~~~~~~ '</body>\n' + '\n' + '</html>' }

function useaxios以外に
res.render('message',Data)としてresponseを使用しているからおかしな値が返ってくるのかなと考えましたがいかがでしょうか?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Twoshi

2021/01/18 07:17

こんにちは! すみません。 確認なのですが、APIを単独で呼び出した場合、想定されているレスポンスが返却されるようになっていますでしょうか?
sakana_motoki

2021/01/18 08:11

こんにちは!確認してくださりありがとうございます! APIを単独で呼び出すというのはどういった意味でしょうか? 無知で申し訳ないです。 API自体はちゃんと動いているような気がします! どのように確かめればよろしいですか?
Twoshi

2021/01/18 09:06

http://localhost:3000/message をPostman や curlコマンドなどで呼び出して想定通りのレスポンスが返却されているかどうかの確認でした。 API自体が想定通りに返却されていなければ、画面側から呼び出しても想定通りの情報が取得できないので...m(_ _)m もし未確認でしたら、Postman というツールが便利かと思います。 使い方については、以下を参考にしてみてはいかがでしょうか? https://www.xlsoft.com/jp/blog/blog/2017/06/23/post-1638/
guest

回答1

0

自己解決

他の方法を試した
node-fetch

投稿2021/02/03 09:15

sakana_motoki

総合スコア16

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問